我想继续向内容脚本发送消息以运行给定 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, anddisconnect()
is called on any of these ports, then theonDisconnect
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/