Google chrome extension 预加载页面消息的后台内容脚本失败
在Chrome扩展中发生了一些奇怪的事情 内容脚本:Google chrome extension 预加载页面消息的后台内容脚本失败,google-chrome-extension,Google Chrome Extension,在Chrome扩展中发生了一些奇怪的事情 内容脚本: console.log('content'); chrome.extension.onRequest.addListener(function(request, sender, sendResponse){ console.log('request received'); sendResponse(); }); chrome.extension.sendRequest( JSON.stringify({'msg': 'pa
console.log('content');
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
console.log('request received');
sendResponse();
});
chrome.extension.sendRequest( JSON.stringify({'msg': 'page_loaded'}) );
它只是侦听扩展消息,并在加载页面时将消息发送到后台
背景脚本:
console.log('bg');
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
sendResponse();
chrome.tabs.sendRequest(
sender.tab.id,
JSON.stringify({'msg': 'page_loaded_bg_receive'}),
function(){
console.log('sendRequest page_loaded_bg_receive callback');
});
});
它可以侦听消息并将消息发送到“发件人”选项卡
而且它似乎正在工作,至少在大多数情况下,在页面日志中显示“请求已收到”
当url输入时,Chrome有时会在用户点击“回车”之前加载键入的地址。这是一种奇怪的行为:页面加载,内容脚本运行,将消息发送到后台,但当后台发送回消息时,它会失败,并显示后台日志消息:
端口错误:无法建立连接。接收端不存在。杂项绑定:184
chromeHidden.Port.dispatchOnDisconnect杂项_绑定:184
这是一个Chrome bug吗?如何将消息发送到“预加载”选项卡
这是复制这种行为的第一个最小样本。我需要在处理消息后多次调用'chrome.tabs.sendRequest',因此调用'sendResponse'不是解决方案。基于本文的解决方案。如果document.webkitVisibilityState不是“隐藏”或“预渲染”,我会运行内容脚本代码,在其他地方我会侦听“webkitvisibilitychange”并等待document.webkitVisibilityState不是“隐藏”或“预渲染”。我认为检查“prerender”就足够了,但当我打开一个新的空选项卡时,它会加载带有document.webkitVisibilityState='hidden'的页面,并且该页面也没有收到背景消息
function isDocumentReady() {
return document.webkitVisibilityState != "hidden" && document.webkitVisibilityState != "prerender";
}
if (isDocumentReady())
main();
else {
function onVisibilityChange() {
if (!isDocumentReady())
return;
document.removeEventListener(
"webkitvisibilitychange",
onVisibilityChange,
false);
main();
}
document.addEventListener(
"webkitvisibilitychange",
onVisibilityChange,
false);
}
当出现这种奇怪的行为时,tab的'index'属性等于'-1'。回调正在调用,所以实际上我可以调用“chrome.tabs.sendRequest”,直到成功。但这似乎很奇怪。那么,解决办法是什么呢?从昨天开始,我一直在尝试这样做,并且不断地得到错误。在弹出窗口中使用sendRequest时,我也会遇到此错误。您有任何冲突的扩展名吗?另外,您不必使用
JSON.stringify
和JSON.parse
,Chrome会自动(反)序列化通道上的请求。没有启用其他扩展。我尝试侦听“Chrome.tabs.onUpdated”或“Chrome.tabs.onMoved”等待tabs“index”属性>=0,但在显示页面时不会发送任何内容。