DOM Exception 12 for window.postMessage

DOM Exception 12 for window.postMessage

本文关键字:window postMessage for Exception DOM      更新时间:2023-09-26

我正在学习构建Chrome扩展,并且我正在尝试遵循官方指南中的指示之一。

我想完成的是:

  1. background.js显示针对目标url的页面操作。
  2. 页面操作在点击时执行脚本。
  3. 已执行的脚本在页面中注入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.postMessagewindow.postMessage混淆。

port.postMessage是一个Chrome扩展特定的API,旨在在扩展内传递消息,而window.postMessage是一个用于与框架通信的JavaScript方法。window.postMessage的第二个参数是必需的,用于验证目标是否允许接收消息。

在您的示例中,使用通配符可能就足够了,因为您正在从页面向其自身发送消息:

window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
                                                                           ^^^