首页 > 解决方案 > Chrome 扩展消息从后台脚本传递到内容脚本错误:接收端不存在

问题描述

我目前正在开发 chrome 扩展程序,但我不断收到此错误:

未选中 runtime.lastError: 无法建立连接。接收端不存在

我正在尝试将消息从我的后台脚本传递到我的内容脚本。后台脚本获取当前选项卡的 url,我正在尝试将该 URL 传递给我的内容脚本。我找到了一些不同的解决方案来解决这个错误,但没有一个对我有用。据我了解,这与后台脚本尝试发送消息时未加载内容脚本有关,尽管我已经尝试了一些解决方法,但对我没有任何效果。这是我的代码:

后台脚本:

//use a query to get the current URL of the tab
    chrome.tabs.query({
        active: true,
        lastFocusedWindow: true
    }, function(tabs){
        var currentTab = tabs[0];
        var currentUrl = currentTab.url;
        //send a message from background script to content script
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            const port = chrome.tabs.connect(tabs[0].id);
            port.postMessage({url: currentUrl});
            port.onMessage.addListener(function(response){
                console.log(response);
            });
        });
    }
    );

内容脚本:

chrome.runtime.onConnect.addListener(function(port){
  port.onMessage.addListener(function(msg){
    if(msg.url.includes("amazon")){
        console.log("You are on amazon.com");
    }
    port.postMessage("This is my response!");
  });
});

这也是我的清单:

{
    "manifest_version": 2,
    "name": "First Browser Extension",
    "version": "1.0.0",
    "description": "Add a better description later.",
    "page_action": {
        "default_icon": "icon.png",
        "default_title": "BrowserExtension",
        "default_popup": "index.html"
    },
    "background":{
        "scripts": ["background.js"],
        "persistent": false
    },
    "content_scripts":[
        {
            "matches": ["https://www.amazon.com/*"],
            "js":  ["content.js"] 
        }
    ],
    "permissions": [
        "tabs",
        "activeTab",
        "https://*/*"
    ],
    "icons": {"48": "icon.png"} 
}

我不知道出了什么问题。任何见解将不胜感激!

编辑:更新的代码

背景

chrome.tabs.query({
    active: true,
    currentWindow: true //changed lastFocusedWindow to currentWindow
}, function(tabs){
    var currentTab = tabs[0];
    var currentUrl = currentTab.url;
    console.log(currentUrl);
    //----------NEW CODE---------------------------
    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if (request.contentScriptQuery === "getURL") {
          sendResponse({url: currentUrl});
          return true;  // Will respond asynchronously.
        }
      });
}
);

内容

chrome.runtime.sendMessage(
    {contentScriptQuery: "getURL"},
    function(urlFromBackground){
        console.log(urlFromBackground.url);
   }
);

标签: javascriptgoogle-chromegoogle-chrome-extensioncontent-scriptmessage-passing

解决方案


推荐阅读