1. 내 페이지 내에 dispatchEvent 로 이벤트를 발생시킨다.
document.dispatchEvent(
new CustomEvent('chrome-extension-test', { "detail" : {"name":"123"} })
);
2. 크롬 익스텐션 content 페이지 내에 이벤트 리스너 등록
./content-script.js
function eventOn() {
document.addEventListener('chrome-extension-test', function (e) {
let name = e.detail.name; //웹페이지에서 전달한 데이터
window.open('https://www.google.com?name='+name); //새탭으로 크롬창을 띄운다
});
}
eventOn();
//url param 검색
let queryString = location.href;
let phone = queryString.split('?name=')[1];
if(phone) {
setTimeout(searchStart,2000);
}
function searchStart() {
alert(phone);
}
새 창을 띄운 후, 새창에서 전달받은 데이터를 alert 띄우는 코드
3. 크롬 익스텐션 background 페이지 내에 content 페이지를 실행하도록 코딩
./background.js
try {
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if(changeInfo.status == 'complete') {
chrome.scripting.executeScript({
files: ['content-script.js'],
target: {tabId: tab.id}
});
}
});
} catch(e) {
console.log(e);
}
4. manifest 설정
./manifest.json
{
"name": "Chrome Extension Test",
"description": "크롬 익스텐션 테스트",
"version": "1.0",
"manifest_version": 3,
"background" : {
"service_worker" : "background.js"
},
"permissions": [
"tabs",
"scripting"
],
"host_permissions": [
"https://my.page.com/test",
"https://*.google.com"
]
}
host_permissions 에는 이벤트를 실행할 페이지의 도메인과, 새창으로 띄울 도메인 둘다 등록 해놔야 함.
반응형
'Chrome Extension' 카테고리의 다른 글
[크롬 익스텐션] 익스텐션 내 파일 접근하기 (0) | 2023.05.25 |
---|---|
[크롬 익스텐션] chrome extension 설치 유무 확인 (0) | 2023.05.10 |
[크롬 익스텐션] url 로 특정 탭 목록 가져와서 url 변경하기 (0) | 2023.05.08 |
[크롬 익스텐션] Message Passing 메시지 및 데이터 전달 (0) | 2023.05.03 |