【问题标题】:Background to content-script of preloading page message fails预加载页面消息内容脚本的背景失败
【发布时间】:2012-07-02 12:54:02
【问题描述】:

Chrome 扩展程序中发生了一些奇怪的事情。

内容脚本:

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');
        });
});

它监听消息并将消息发送到发件人选项卡。

而且它似乎工作正常,至少在大多数情况下页面日志中出现“收到请求”。

虽然输入 Chrome 的 url 有时会在用户点击“输入”之前加载输入的地址。这是一个奇怪的行为:页面加载,内容脚本运行,将消息发送到后台,但是当后台发送消息时 - 它失败并显示后台日志消息:

端口错误:无法建立连接。接收端不存在。 miscellaneous_bindings:184 chromeHidden.Port.dispatchOnDisconnect miscellaneous_bindings:184

这是 Chrome 错误吗?如何将消息发送到预加载选项卡?

这是重现此类行为的人工最小样本。我需要在处理完消息后多次调用“chrome.tabs.sendRequest”,因此调用“sendResponse”不是解决方案。

【问题讨论】:

  • 当出现这种奇怪的行为时,选项卡的“索引”属性等于“-1”。并且回调正在调用,所以实际上我可以调用“chrome.tabs.sendRequest”直到成功。但这似乎很奇怪。
  • 那么,解决方案是什么?从昨天开始我一直在尝试这样做并不断收到错误。当我在弹出窗口中使用 sendRequest 时,我也会收到此错误。
  • 你有任何冲突的扩展吗? PS。您不必使用JSON.stringifyJSON.parse,Chrome 会自动(反)序列化通道上的请求。
  • 没有启用其他扩展。
  • 我尝试监听 'chrome.tabs.onUpdated' 或 'chrome.tabs.onMoved' 以等待选项卡 'index' 属性为 >=0 时,但在页面时没有发送显示。

标签: google-chrome-extension


【解决方案1】:

基于文章https://developers.google.com/chrome/whitepapers/pagevisibility的解决方案。如果 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);

}

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多