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

问题描述

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

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

背景.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。

内容.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 没有出现……哈哈!

标签: javascriptgoogle-chrome-extensionsendmessagecontent-script

解决方案


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

内容.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 的全局范围内 - 而不是在您用来处理选项卡的循环内。


推荐阅读