我想在选项卡加载新页面后从内容脚本运行回调函数。
这是我的代码:
content_script.js
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
if (request.id == "content_script") {
// open google.com
chrome.runtime.sendMessage({
"id" : "openUrl",
"url" : "https://google.com"
}, function(response) {
});
// call background script
// go to the claim code page
chrome.runtime.sendMessage({
"id" : "background"
}, function() {
alert("test");
});
}
});
background.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.id == "openUrl") {
var tabId = sender.tab.id;
var url = msg.url;
openUrl(tabId, url);
} else if (msg.id == "background") {
setTimeout(function() {
sendResponse();
}, 5000);
}
});
function openUrl(tabId, url) {
chrome.tabs.update(tabId, {
url : url,
active : false
}, function() {
console.log("open tab url callback");
});
};
我还将源代码上传到谷歌驱动器,您可以使用以下链接下载它: https://drive.google.com/open?id=15zSn40z4zYkvCZ8B-gclzixvy6b0C8Zr
你可以看到警报测试没有显示!
但是,如果我删除打开新网址的代码,则会出现提醒(“test”)!
我不确定为什么!但是当我打开新网址时,javascript似乎丢失了对回调函数的引用。
我该如何解决这个问题?什么是正确的方法?
谢谢
答案 0 :(得分:0)
消息回调返回后,sendResponse
函数变为无效,除非您从事件侦听器返回true ,表示您希望异步发送响应。 (https://developer.chrome.com/extensions/runtime#event-onMessage)
在background.js中添加return true;
以使此处理程序异步。
现在,您在background.js的Attempting to use a disconnected port object
调用中收到错误sendResponse();
,是的,这是页面导航并丢失内容脚本正在运行的上下文的结果英寸
没有办法让这项工作:您想要调用alert()
的上下文不再存在。
请尝试使用chrome.tabs.sendMessage。但这意味着您必须在顶层设置侦听器,而不是在任何回调内部。消息传递很难。