javascript chrome.tabs.sendMessage:'无法建立连接,接收端不存在'

y53ybaqx  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(228)

我正在尝试开发一个Chrome扩展,我的manifest.json是:

{
  "name" : "Extension",
  "version" : "2.2",
  "description" : "Web collaboration chrome extension",
  "permissions": ["tabs", "activeTab"],
  "browser_action": {
     "default_icon": "logo.png"
  },
  "icons": {
    "128": "icon128.png"
  },
  "content_scripts": [{
     "matches": ["*://*/*"],
     "run_at": "document_idle",
     "match_about_blank": true,
     "all_frames": true,
     "js": ["content.js", "addon.js"]
  }],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_security_policy": "script-src 'self'   https://expample.com/umd/example.min.js; object-src 'self'",
  "manifest_version": 2
}

background.js是:

chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
      let activeTab = tabs[0];
      chrome.tabs.sendMessage(activeTab.id, {"message": "request", "payload":    preferences}, function(response) {
        if (!chrome.runtime.lastError) {
          console.log('response', response);
        }else{
          console.log(chrome.runtime.lastError);
        }
      });
    });

content.js是:

chrome.runtime.onMessage.addListener(
                  function(request, sender, sendResponse) {
                     if(request.message === "request") console.log('response received', request.payload)
                     sendResponse({status: "done"});
                  return true;
                  }
               )

Chrome Inspector出现错误:chrome.runtime.lastError {message:'无法建立连接。接收端不存在。'}。
需要帮助吗

fykwrbwg

fykwrbwg1#

更新代码后,您需要重新加载打开的标签页。否则,内容脚本将无法正确注入。因此,选项卡端(content-script)上的侦听器未启动/不存在。
然而,更好的解决方案是通过代码注入内容脚本。例如,在extension-invocation上使用以下代码:

/*re-inject content-scripts on each open of extension*/
for (const tab of tabs) {
    chrome.scripting.executeScript({
        target : {tabId : tab.id},
        files : [ "scripts/content.js" ],
    });
}

相关问题