微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未经检查的 runtime.lastError:在收到响应之前消息端口已关闭我该如何解决?

如何解决未经检查的 runtime.lastError:在收到响应之前消息端口已关闭我该如何解决?

我有这个问题。我看到了这个 question 并尝试了它的解决方案,但它似乎不起作用。错误消失了,但代码没有做它应该做的事情。

所以,基本上,我有一个后台脚本,它使用 XMLHTTPSrequest 在所有 http 或 https 页面中注入内容脚本。

background.js:

chrome.browserAction.onClicked.addListener(function (event) {
    show_floater = !show_floater;
    // inject content script in tabs
    let xhr = new XMLHttpRequest();
    xhr.open("GET","https://127.0.0.1/js/test1.js",true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            chrome.tabs.query({ currentwindow: true },(tabs) => {
                tabs.forEach(function(e) {
                    if (/http:/.test(e.url) || /https:/.test(e.url)) {
                        chrome.tabs.executeScript(e.tabId,{ code: xhr.responseText },() => {
                            connect(show_floater);
                            console.log(e.url);
                        });
                    }
                    else
                        console.log('e: ' + e.url);
                });
            });
        }
    }
    xhr.send();
});

内容脚本然后在页面上执行它的魔术,并在用户操作发生时将消息发送回 bg。

content.js

 chrome.runtime.sendMessage({},function (response) {
     console.log('sent');  
     let msgData = { text: "am I connected?" };
     chrome.runtime.sendMessage(JSON.stringify(msgData));
 });

这里是 bg 处理消息的方式:

chrome.runtime.onMessage.addListener(function (msg,sender,sendResponse) {
    console.log('I AM HERE');
    chrome.tabs.query({ active: true,currentwindow: true },(tabs) => {
        if (/http:/.test(e.url) || /https:/.test(e.url)) {
            const port = chrome.tabs.connect(tabs[0].id);
            msg = JSON.parse(msg);
            if (msg.text == "am I connected?") {
                //do stuff
            }
        }
    });
    // return true;
});

我正在查看的答案说在最后添加了“返回真”。我试过了,错误消失了,但没有出现 console.log... HALP!

解决方法

不需要所有那些过于复杂的东西。
只需发送消息并回复:

content.js

chrome.runtime.sendMessage({ text: 'am I connected?' },response => {
  console.log(response);
});

背景.js

chrome.runtime.onMessage.addListener((msg,sender,sendResponse) => {
  if (msg.text == 'am I connected?') {
    console.log(msg,'sender URL:',sender.url);
    //do stuff
    sendResponse({ foo: 'bar' });
  }
});

请注意,此 onMessage 侦听器应仅添加一次,在 background.js 的全局范围内 - 而不是在用于处理选项卡的循环内。

,

Chrome 扩展程序存在问题。

到这里 chrome://extensions 并禁用所有扩展程序并尝试!它会起作用。

但是尝试一一启用扩展,才知道是什么扩展导致这个错误

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。