javascript - 选项卡 URL 更改后如何继续从扩展程序发送消息内容脚本?

标签 javascript google-chrome-extension

我想继续向内容脚本发送消息以运行给定 URL 的不同函数。每当我访问一个新的 URL 时,消息就会停止。如何才能在加载新选项卡 URL 时暂停消息传递,然后在加载选项卡时继续消息传递?

popup.js

function begin(params) {

    chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
        console.log("connecting");
        var port = chrome.tabs.connect(tabs[0].id, {name: "testing"});
        port.postMessage({test: "test1"});
        port.onMessage.addListener(function(msg) {
            if (msg.response == "test1 received") {
                console.log(msg.response);
                port.postMessage({test: "test2"});
            } else if (msg.response == "test2 received") {
                console.log(msg.response);
                port.postMessage({test : "test3"});
            } else if (msg.response == "test3 received") {
                console.log(msg.response);
                port.postMessage({test : "test4"});
            }
        });
    });
}

contentscript.js

chrome.runtime.onConnect.addListener(function(port) {
  console.assert(port.name == "testing");
  port.onMessage.addListener(function(msg) {
    if (msg.test === "test1") {
        console.log(msg.test);
        // Do stuff and click on new url //
        port.postMessage({response: "test1 received"});

    } else if (msg.test === "test2") {
        console.log(msg.test);
        // Do stuff and click on new url //
        port.postMessage({response: "test2 recieved"});
  });
});

最佳答案

您可能需要重新建立连接,因为根据official guide的描述,连接在以下情况下关闭:

  • There are no listeners for runtime.onConnect at the other end.
  • The tab containing the port is unloaded (e.g. if the tab is navigated).
  • The frame from where connect was called has unloaded.
  • All frames that received the port (via runtime.onConnect) have unloaded.
  • runtime.Port.disconnect is called by the other end. Note that if a connect call results in multiple ports at the receiver's end, and disconnect() is called on any of these ports, then the onDisconnect event is only fired at the port of the sender, and not at the other ports.

关于javascript - 选项卡 URL 更改后如何继续从扩展程序发送消息内容脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38175665/

相关文章:

javascript - 仅向具有固定标题 Angularjs 的表体添加滚动

google-chrome-extension - Chrome 扩展程序性能

javascript - 我可以编写 chrome 扩展来在页面加载时更改页面或网站的 CSS 吗?

javascript - 使用 jQuery 修改 CSS 类的名称 - 无法加载

javascript - 脚本标记中的 Google Analytics 脚本或脚本链接

javascript - 数组内过滤数组

javascript - 是否可以从 Chrome 中的内容脚本执行跨源 XMLHttpRequest?

JavaScript - 迭代表单输入并将值收集为对象中的键值对

javascript - chrome 扩展 chrome.storage 如何同时进行大量获取和设置并避免竞争条件?

google-chrome - 如何用我在userscripts.org上找到的代码编译Google Chrome扩展程序?