我正在学习构建Chrome扩展程序,我正在尝试按照官方指南here中的一条说明进行操作。
我想要完成的是:
到目前为止,真好!我使用以下脚本注入页面。
var injectJS = function(url, cb) {
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url;
if (cb)
s.onload = cb;
h.appendChild(s);
};
injectJS(chrome.extension.getURL('script/do_something.js'));
现在,我希望注入的脚本能够与扩展程序进行通信 看起来我正在寻找的是文档中描述的内容。
https://developer.chrome.com/extensions/content_scripts.html#host-page-communication
问题是,当我尝试window.postMessage
时,控制台显示错误“DOM Exception 12”。
编辑:解决了运行示例代码的第一个问题
我得到的另一个错误来自于port.postMessage
:
Uncaught Error: Attempting to use a disconnected port object
以下是代码:
var port = chrome.runtime.connect();
// Respond to messages from the injected script to collect results
window.addEventListener('message', function(e) {
if (e.source != window)
return;
if (e.data.type && (e.data.type == 'FROM_PAGE')) {
console.log('Content script received: %s', e.data.text);
port.postMessage(e.data.text);
}
}, false);
基本上我正在尝试在页面重新加载时暂时保留一些数据。内容脚本/注入脚本收集数据,然后加载下一页。后台脚本应保存结果,直到所有页面都已加载。
答案 0 :(得分:6)
请勿将contentscript.js示例中的port.postMessage
与window.postMessage
混淆。
port.postMessage
是特定于Chrome扩展程序的API,用于在扩展程序中传递消息,而window.postMessage
是用于与框架通信的JavaScript方法。 window.postMessage
的第二个参数是必需的,用于验证是否允许目标接收消息。
在您的情况下,使用通配符可能就足够了,因为您正在从页面向自身发送消息:
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
^^^