本文介绍了如何处理“未检查的runtime.lastError:在收到响应之前关闭消息端口"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我是chrome扩展程序的新手的任何明显错误,但是我们已经讨论了Chrome消息传递API的错误,此处,以及此处过去,常见的反应是禁用现有的Chrome扩展程序,其中之一引起了错误".这是可以做到的最好的吗?返回true还是返回侦听器回调函数的Promise并使用 sendResponse 不能解决以下问题:我.

Forgive me for any glaring mistakes as I am new to chrome extensions, but this error with Chrome's message passing API has been discussed here, here, and here in the past and the common response is along the lines of 'disable existing Chrome extensions, one of them is causing the error'. Is this the best that can be accomplished? Are we supposed to just roll over and accept the fact that our extensions will conflict with others? Returning true or returning a Promise for the listener callback function and using sendResponse does not solve the problem for me.

当前,我只能通过禁用所有其他chrome扩展程序,删除扩展程序并加载解压缩的扩展程序来获取存储在 chrome.storage.local 中的新值(无错误)有趣的是,该代码似乎只能在developer.chrome.com上运行,而在 manifest.json 中的其他匹配" URL上根本不起作用.

Currently, I can only get the new value stored in chrome.storage.local (no errors) by disabling all other chrome extensions, removing the extension and loading back up the unpacked extension. The code interestingly only seems to work on developer.chrome.com, it doesn't work at all on the other "matches" URLs in manifest.json.

我认为 await async 运算符在解决此问题方面有一定意义,但我不确定如何正确实现.

I think that there is some significance in the await and async operators in solving this issue but I am unsure how to properly implement it.

manifest.json:

{
    "manifest_version": 2,
    "name": "my extension",
    "version": "1.0",
    "description": "its my extension",
    "permissions": [
        "declarativeContent",
        "storage",
        "activeTab"
    ],
    "content_scripts": [
        {
          "matches": [
            "*://developer.chrome.com/*",
            "*://bbc.co.uk/*",
            "*://theguardian.com/*",
            "*://dailymail.co.uk/*"
          ],
          "js": ["content.js"]
        }
      ],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "content_security_policy": "script-src 'self' https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js; object-src 'self'",
    "page_action": {
        "default_popup": "popup.html"
    },
    "icons": {
        "16": "images/icon16.png",
        "32": "images/icon32.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
      }
}

popup.html:

<!DOCTYPE html>
  <html>
    <head>
      <title>my extension</title>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="popup.js"></script>
      <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
      <h1>my extension</h1>
      <h2>Article: <span id="article-headline"></span></h2>
      <button id="detect-article">Detect Article</button>
    </body>
  </html>

popup.js:

$(document).ready(function() {
    $("#detect-article").click(function() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            chrome.tabs.sendMessage(tabs[0].id, {request: "Requesting headline"}, function(response) {
                console.log("Requesting headline")
            });
        });
    });
})

function getHeadline(changes) {
    let changedValues = Object.keys(changes);
    //console.log(changedValues);

    for (var item of changedValues) {
        console.log("new value: " + changes[item].newValue);
        $("#article-headline").text(changes[item].newValue)
    }
}

chrome.storage.onChanged.addListener(getHeadline);

content.js:

function handleRequest(message, sender, sendResponse) {
    console.log("Request recieved");
    let headlineList = document.getElementsByTagName("h1");
    chrome.storage.local.set({headline: headlineList[0].innerText}, function() {
        console.log("'" + headlineList[0].innerText + "' stored in local storage");
    });
    return true;
}

chrome.runtime.onMessage.addListener(handleRequest);

background.js:

chrome.runtime.onInstalled.addListener(function() {
    chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
      chrome.declarativeContent.onPageChanged.addRules([{
        conditions: [
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { hostContains: 'developer.chrome.com' },
          }),
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { hostContains: 'bbc.co.uk' },
          }),
          new chrome.declarativeContent.PageStateMatcher({
            pageUrl: { hostContains: 'theguardian.com' },
          }),
          new chrome.declarativeContent.PageStateMatcher({
              pageUrl: { hostContains: 'dailymail.co.uk' },
          }),
        ],
      actions: [new chrome.declarativeContent.ShowPageAction()]
    }]);
  });
});

非常感谢您抽出宝贵时间来查看/重新查看此问题,我所寻找的并不是与上述禁用现有扩展名"有关的解决方案.

Many thanks for taking the time to look/re-look at this issue, solutions pertaining to the aforementioned 'disable existing extensions' are not what I am looking for.

推荐答案

当您为sendMessage指定回调时,您是在告诉API 您需要响应,因此当您的内容脚本不需要使用sendResponse进行响应,API认为发生了可怕的事情,并报告了该情况!

When you specify a callback for sendMessage you're telling the API that you NEED a response so when your content script doesn't respond using sendResponse the API thinks something terrible happened and reports it as such!

您不需要任何回复:

  • 删除sendMessage中的回调

  • Remove the callback in sendMessage

chrome.tabs.sendMessage(tabs[0].id, {request: "Requesting headline"});

  • 删除 return true -当前所做的只是告诉API无限期地打开消息传递端口,这将永远不会被您使用,因此,它只是一个内存泄漏源./p>

  • Remove return true - all it does currently is telling the API to keep the messaging port open indefinitely, which will never be used by you, so it's just a memory leak source.

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      // do something
      // don't call sendResponse, don't return true
    });
    

  • 您需要回复:

    • sendResponse

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      sendResponse('whatever');
    });
    

    您需要来自异步运行的代码的响应,例如 chrome API回调:

    You need a response from asynchronously running code such as chrome API callback:

    • 保持返回真实

    在回调内调用 sendResponse(someImportantData)

    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      chrome.storage.local.set({foo: 'bar'}, () => {
        sendResponse('whatever');
      });
      return true;
    });
    

    这篇关于如何处理“未检查的runtime.lastError:在收到响应之前关闭消息端口"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-06 02:22