chrome.tabs.sendMessage 显示错误无法建立连接。接收端不存在

Ash*_*h S 6 javascript google-chrome-extension

我试图从 background.js 调用内容脚本,但每次我看到这个错误。无法建立连接。接收端不存在。

我在哪里调用内容脚本。

chrome.webRequest.onCompleted.addListener(function (details) {
    if (TRACKED_WEB_REQUEST_TYPES.indexOf(details.type) >= 0 &&    TRACKED_WEB_REQUEST_METHODS.indexOf(details.method) >= 0) {
        var res = false;
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            if (tabs.length > 0) {
                chrome.tabs.sendMessage(tabs[0].id, { greeting: "hello" }, function (response) {
                if (chrome.runtime.lastError) {
                    // An error occurred :(
                    console.log("ERROR: ", chrome.runtime.lastError);
                }
                if (response) {
                    console.log(response.result);
                    res = response.result;
                    console.log(res);
                }
            });
        }
    });
Run Code Online (Sandbox Code Playgroud)

content.js 看起来像这样..

  chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {

  sendResponse({ result: true });
  });
Run Code Online (Sandbox Code Playgroud)

在 manifest.json 文件中,我有以下条目..

{
  "matches": ["http://*/*", "https://*/*"],
  "js": ["content.js"],
  "run_at": "document_end"
}
  ],
  "permissions": [
"tabs"]
Run Code Online (Sandbox Code Playgroud)

任何想法我在这里做错了什么。