DOM Exception 12 for window.postMessage
DOM Exception 12 for window.postMessage
我正在学习构建Chrome扩展,并且我正在尝试遵循官方指南中的指示之一。
我想完成的是:
- background.js显示针对目标url的页面操作。
- 页面操作在点击时执行脚本。
- 已执行的脚本在页面中注入javascript。
到目前为止,一切顺利!我使用以下脚本将其注入到页面中。
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);
基本上,我试图在页面重新加载时暂时保存一些数据。内容脚本/注入脚本收集数据,然后加载下一页。后台脚本应该保存结果,直到所有页面都加载完毕。
不要将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!" }, "*");
^^^
相关文章:
- window.postMessage与ajax的优缺点
- 使用postMessage指定window.frame
- Javascript window.postmessage()帮助-don'我不了解用法
- 安全使用window.postMessage,是“;if(event.source!==window){return;}
- 我可以使用window.postMessage方法从iframe中的网页通信到包括该iframe的UIWebView吗
- jQuery $.Deferred with window.top.postMessage()
- setTimeout(0) vs window.postMessage vs MessagePort.postMessa
- window.parent.postMessage父级检查iframe发送的消息
- window.postMessage从web_accessible_resource到内容脚本
- 当Window.postMessage()被激发时触发的事件
- TypeError:Window.postMessage的参数不足
- Window.Parent.Postmessage with Parameter
- window.postmessage - event.data 始终为空
- 是否允许在chrome扩展中使用window.postMessage() ?
- DOM Exception 12 for window.postMessage
- Do window.postMessage()适用于不同服务器上的不同应用程序
- Window.postMessage() issue
- JSONP or window.postMessage & MessageChannel
- 帮助浏览器窗口集合window.postmessage
- Node.js executing window.postmessage