我在popup.js、content.js和background.js下面编写代码。它可以通信 popup.js <-> background.js。但是嵌入在网站中的content.js无法与background.js通信。 console.log中的runtime.sendMessgae只需说“undefine”。如何在 content.js 之间通信 background.js?
manifest.js
{
"manifest_version": 3,
"name": "test_project",
"short_name": "test",
"version": "1.0.0",
"description": "",
"action": {
"default_popup": "page/index.html"
},
"permissions": ["identity","scripting","storage","alarms"],
"content_scripts": [
{
"matches": ["file:///*"],
"js": [
"popup.bundle.js"
]
},
{
"matches": [ "*://mail.google.com/*" ],
"js": [
"content.bundle.js"
],
"run_at": "document_start"
}
],
"background": {
"service_worker": "background.bundle.js"
},
"oauth2": {
"client_id": "",
"scopes": [
"https://www.googleapis.com/auth/gmail.compose"
]
},
"web_accessible_resources": [{
"resources": [
"extension.bundle.js",
"extension.bundle.js.map",
"gmailJsLoader.bundle.js",
"gmailJsLoader.bundle.js.map"
],
"matches": ["<all_urls>"]
}],
"host_permissions": [
"https://*/*"
],
"options_page": "page/options.html"
}
背景.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('📥 메시지 수신:', request);
if (request.action === 'getAuthToken') {
console.log('🚀 getAuthToken 호출 시작');
chrome.identity.getAuthToken({ interactive: true }, (token) => {
if (chrome.runtime.lastError) {
console.error('❌ 오류 발생:', chrome.runtime.lastError);
sendResponse({ success: false, error: chrome.runtime.lastError.message });
} else {
console.log('✅ 액세스 토큰:', token);
sendResponse({ success: true, token });
}
});
// 비동기 응답을 대기
return true;
}
});
popup.js
// It can work
document.getElementById('inesrtAddressBookButton').addEventListener('click', () => {
chrome.runtime.sendMessage(EXTENSION_ID, { action: 'getAuthToken' }, (response) => {
console.log(response)
})
})
内容.js
// It loaded on gmail
const loaderId = setInterval(() => {
if (!window._gmailjs) {
return;
}
clearInterval(loaderId);
startExtension(window._gmailjs);
}, 100);
function startExtension(gmail) {
console.log("Extension loading...");
window.gmail = gmail;
gmail.observe.on("load", () => {
gmail.observe.on("compose", (compose) => {
var content_html = $(`
<div>
test
</div>
`);
gmail.tools.add_compose_button(compose, content_html, function() {
getAuthTokenAndFetchData(compose)
}, "");
});
});
}
function getAuthTokenAndFetchData(compose) {
chrome.runtime.sendMessage(EXTENSION_ID, { action: 'getAuthToken' }, (response) => {
console.log(response)
})
}
根据您在
window
上访问页面变量的事实来判断,代码在 DOM script
元素或显式指定的 MAIN
世界中运行(更多信息)。该脚本不再是扩展的一部分,而只是一个无权限的网页脚本,无法访问仅存在于隔离内容脚本中的chrome
。
要向扩展程序发送消息,您需要使用externally_connectable
消息传递:https://developer.chrome.com/docs/extensions/develop/concepts/messaging#external-webpage