Chrome浏览文档上content script communication建议在发送代码(这里是网页)中使用window.postMessage
,并在侦听代码中使用window.addEventListener("message", ...)
(这里,内容sc Chrome扩展的注入,注入页面)。从技术上讲,任何一种自定义DOM事件也可以做到这一点,但postMessage
/message
已经有内置的支持。
你应该能够解除从代码示例代码几乎一字不差:
本地网页:
// right after we get auth_token saved to a variable...
window.postMessage({ auth_token: auth_token }, "http://www.mypagedomain.com");
(确保http://www.mypagedomain.com
更改为您的实际协议/域) (在Chrome扩展中,收听)
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window) {
return;
}
console.log("auth_token received: " + event.data.auth_token);
}, false);
从事件监听器中,如果需要,可以使用message passing将auth_token
传递到您的背景页面。
编辑:
你的清单应包括这样的事情(注意使用以下run_at
页面加载前注入脚本):
...
"content_scripts": [
{
"matches": ["http://www.mypagedomain.com/*"],
"js": ["contentscript.js"],
"run_at": "document_start"
}
],
...
请参阅Google关于[内容脚本通信]的文档(http://developer.chrome.com/extensions/content_scripts.html#host-page-communication)。内容脚本和网页共享DOM,因此在内容脚本或网页中触发的DOM事件对两者都是可见的。 – apsillers