我想继续向内容脚本发送消息,以便在给定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"});
});
});
答案 0 :(得分:1)
您可能需要重新建立连接,因为根据official guide的说明,在以下情况下会关闭连接:
- 另一端没有
runtime.onConnect
的听众。- 卸载包含该端口的标签(例如,如果该标签已导航)。
- 调用connect的框架已卸载。
- 收到端口的所有帧(通过
runtime.onConnect
)都已卸载。runtime.Port.disconnect
被另一端调用。请注意,如果连接呼叫在接收方端产生多个端口,并且在任何这些端口上调用disconnect()
,则onDisconnect
事件仅在发送方的端口触发,而不是在其他港口。