javascript - 多个 chrome.runtime.onMessage-Listeners - 断开端口错误

标签 javascript jquery json google-chrome-extension indexeddb

我正在开发一个使用 indexedDB-Wrapper 的 chrome 扩展 Dexie , 几个 jQuery 库和 syncfusions eGrid显示和修改数据库。我知道这个问题以前被问过好几次,但现在我发现了一些奇怪的行为。

我的设置:

  • 后台脚本
  • 内容脚本(注入(inject)网站)
  • index.html(用于显示网格)
  • list .json

当我重新加载我的扩展时,一切都很好。我在我的内容脚本中注入(inject)了一个可滚动的名称列表。这在我重新加载选项卡时也有效。但是,当我在 (官方文档中的 popup.html) 之前打开 index.html 时,后台脚本的 sendResponse 在一段时间后停止工作。重新加载选项卡将无济于事。我搜索了几个小时,在 google bugtracker 上发现了很多类似的案例和一些条目,他们声称这个问题已经解决了。我也知道如果我有像 indexedDB 这样的异步函数,我必须使用 return true。

因此,为了给您更多信息,我将列出我的缩短脚本。

内容脚本

chrome.runtime.sendMessage({greeting: 'getNames'},function(response){
    $('.names-container').append(response.farewell);
});
chrome.runtime.sendMessage({greeting: 'getData'+name},function(name){
    chrome.runtime.sendMessage({greeting: 'delete'},function(response){
        console.log(response.farewell);
    });
    chrome.runtime.sendMessage({greeting: 'set'}, function(response) {
        console.log(response.farewell);
    });
});

背景脚本

chrome.runtime.onMessage.addListener(function(message,sender,sendResponse){
  if(message.greeting == 'getNames'){
    // Get array of names from idb and send it back
    idb.opendb().then(function(a){
      sendResponse(a);
    });
    return true;
  } else if(message.greeting.indexOf('getData') >= 0){
    // get more information for selected name
    idb.opendb().then(function(a){
      sendResponse(a);
    });
    return true;
  } else if(message.greeting == 'delete'){
    // further processing to delete some stuff
    idb.opendb().then(function(a){
      sendResponse(a);
    });
    return true;
  } else if(message.greeting == 'set'){
    // synchronous function
    // do something ...
    return false;
  } else {
    // Do something
  }
  //return true;
});

funtion indexhtml(){
  chrome.runtime.sendMessage(
    "notifications",
    function (response) {
      console.log(response);
    }
  );
}

Index.html

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  if(request == 'notifications'){
    notifications();
  }

  sendResponse("Message received from background-page for "+request);
});

list

{
    "manifest_version": 2,
    "name": "MyExtension",
    "description": "Some desc...",
    "version": "0.2",
    "background": {
        "scripts": ["js/jquery-2.1.4.min.js", "js/background.js", "...",
        "persistent": true
    },
    "default_locale": "en",
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["js/jquery-2.1.4.min.js"]
        },
        {
          "matches": ["https://domain.tld/*"],
          "js": ["js/jquery-2.1.4.min.js", "js/contentscript.js"],
          "css" : ["css/contentscript.css",
          "run_at": "document_start"
        }
    ],

    "icons": {
        "16": "images/icon-16x16.png",
        "48": "images/icon-48x48.png",
        "128": "images/icon-128x128.png"
    },
    "browser_action": {
        "default_icon": "images/icon-128x128.png"
    },
    "permissions": [
        "cookies", "tabs", "alarms", "webRequest", "webRequestBlocking", 
        "contextMenus", "<all_urls>", "storage"
    ],

    "content_security_policy": "script-src 'self' 'unsafe-eval'; 
    object-src 'self'"
}

我很难调试此行为,因为我无法准确知道错误 Attempting to use a disconnected port object 何时出现。看起来端口在执行 sendResponse 后没有正确关闭,并且只有在打开 index.html 时才关闭。

最后是缩短的错误消息:

Error: Attempting to use a disconnected port object
    at Error (native)
    at PortImpl.postMessage (extensions::messaging:65:22)
    at Port.publicClass.(anonymous function) [as postMessage] (extensions::utils:94:26)
    at responseCallback (extensions::messaging:163:16)

idb-Functions 是定制的,不会像我在这里写的那样工作,但我只是想展示我在那里做的事情。当结果可用时,我使用 .then()sendReponse,如果异步,则 return true; 等待结果。我还在每个脚本中搜索了 onMessagesendMessage。列出的与 onMessage/sendMessage 相关的函数都是我使用的,它们没有在其他地方使用。我使用 indexhtml() 的计时器来保存包含指定时间间隔内通知的数组,然后在 index.html 中执行一个函数以重新加载通知。

index.html 选项卡通过 browserAction 打开:

chrome.browserAction.onClicked.addListener(function(tab){
    chrome.tabs.create({url: chrome.extension.getURL('index.html')});
});

最佳答案

好吧,我在调试越来越多后自己找到了答案。这里的问题是,我正在使用多个 (2) onMessage-Listeners。没有特定的监听器只能监听发送到我的内容页面 (index.html) 的消息。每次我打开 index.html 时,如果在我的内容脚本中使用了 sendMessage,则会首先调用附加的 onMessage-Listener。我不知道这个嵌入到 index.html 中的 onMessage-Listener 也每次都会被调用。然后我在我的内容脚本中更改了 sendMessage 的目的地 - 结果相同。谷歌文档中也有关于此主题的注释:

Note: If multiple pages are listening for onMessage events, only the first to call sendResponse() for a particular event will succeed in sending the response. All other responses to that event will be ignored.

Link here

第二个问题是,我在 if 子句之外使用了 sendResponse,这样它每次都会被调用。所以最后我只需要将 sendResponse 放在 if 子句中,这样只有当来自后台页面的指定消息通过 sendMessage 被调用时它才会被调用。

背景脚本

  • 通过搜索 chrome-extension://extid/index.html 获取 tab.id
  • 仅将消息发送到 index.html
chrome.windows.getAll({populate:true},function(windows){
  windows.forEach(function(window){
    window.tabs.forEach(function(tab){
      if(tab.url.indexOf(chrome.extension.getURL('index.html')) >= 0){
         chrome.tabs.sendMessage(tab.id,{ greeting: "notifications"}, function(response){
           console.log(response);
         });
      }
    });
  });
});

Index.html

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
        if(message.greeting == "notifications-trades"){
            Notifications();
            sendResponse("Message received from bg "+message.greeting);
            //if async add return true;
        } else {
            //Do something
        }
});

关于javascript - 多个 chrome.runtime.onMessage-Listeners - 断开端口错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36165416/

相关文章:

c# - 使用大集合反序列化 JSON

javascript - CKEditor构建自定义版本

jquery - 使用 json 获取多个页面的 facebook 点赞

JQuery .load() inside div

jquery - 更改 <div> 的背景颜色时.delay() 不起作用

javascript - 从 URL 解析 JSON

json - 你如何在 Go 中解码为正确的顺序?

javascript - 拒绝获取不安全 header "Content-Length"/从外部 mp3 读取 ID3 标签

javascript - 向对象添加条目

javascript - Jquery:如何在同一页面上打开链接(即点击链接但地址栏链接没有改变)?