-
[chrome extension] How to send message content script to background.jsFrontend/chrome extension 2020. 3. 23. 14:56
chorme extension을 만들때 주요 개념이 있다.
간단히 정리하자면,
- background.js : 말 그대로 백그라운드 작업을 처리한다. 작동 방식은 '항시동작/이벤트전달'로 목적에 맞춰 작성하면된다.
- content script : 현재 웹 페이지에 커스텀 html을 injection 하여 인터렉트를 위해 사용된다.
- popup : 브라우저 상단 url입력 오른쪽에 표시되는 ui이다.
그 밖에 permission 관련 등은 검색하면 많이 나온다.
content script to background.js 통신하는 방법을 소개하고자 한다.
현재 페이지에서 텍스트를 선택하면 content script가 동작하여 버튼이 생성되고, 클릭시 background.js에 그 값을 전달해 저장한다.
chrome.runtime.sendMessage API를 사용하면 객체 {} 형태로 원하는 값을 전달 할 수 있다.
// contentscript.js chrome.runtime.sendMessage({greeting: 'backgroundhello'}, (response) => { console.log("[contentscript] chrome.runtime.sendMessage()"); console.log(response.farewell); });
Chrome.runtime.onMessage.addListener() API를 통해 전달받은 메시지를 처리하고 반환한다.
// background.js chrome.runtime.onMessage.addListener( (request, sender, sendResponse) => { console.log('[background] chrome.runtime.onMessage.addListener()'); if (request.greeting === 'backgroundhello') { console.log("[background] request:" + request.greeting); // TODO sendResponse({ farewell: 'contentgoodbye' }); } });
실행결과
content script console:
background console:
위와 같은 방식으로
content script와 popup간의 통신도 가능하다.
MESSAGE PASSING
'Frontend > chrome extension' 카테고리의 다른 글