内容脚本未从后台脚本接收消息 (Mv3)

2024-01-06

我制作了这个简单的消息传递示例 chrome 扩展,其中应该将消息从后台脚本发送到内容脚本。不幸的是,内容脚本似乎没有收到该消息。

后台脚本:

// background.js

function sendMessage(tabId, hostname) {
    console.log("Sending message to tabId: ", tabId)
    chrome.tabs.sendMessage(tabId, {hostname: hostname}, (resp) => {console.log("response: ", resp)});
}

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
    if (changeInfo.url) {
        console.log(changeInfo.url)
        var hostname = new URL(changeInfo.url).hostname;
        sendMessage(tabId, hostname)

    }
});

内容脚本:

// content.js

console.log("injected");

function logMessage(message) {
    console.log("Message from background: ", message)
}

chrome.runtime.onMessage.addListener(
    (request, sender, sendResponse) => {
        logMessage(request.hostname)
    }
);

清单(v3):

// manifest.json

{
  "name": "Messaging test",
  "description": "",
  "version": "1.0",
  "manifest_version": 3,

  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["tabs"],
  "content_scripts": [
    {
      "matches": [
        "<all_urls>",
        "https://*/*",
        "http://*/*"
      ],
      "js": ["content.js"]
    }
  ]
}

我确保重新加载扩展并使用新选项卡进行测试。

以下是后台脚本的开发控制台输出:后台脚本的开发控制台输出 https://i.stack.imgur.com/NJJtf.png

这是内容脚本的开发控制台输出(注入 google.com):内容脚本的开发控制台输出 https://i.stack.imgur.com/9s7ue.png

因此,内容脚本被注入,但没有从后台脚本接收消息。我记得这在清单 v2 中工作,所以我不确定出了什么问题。有任何想法吗?


默认情况下,内容脚本在 DOMContentLoaded 之后运行,但是onUpdated当选项卡开始加载 URL 时会触发事件,因此当调用 sendMessage 时,此选项卡中还没有内容脚本。

解决方案:指定"run_at": "document_start" https://developer.chrome.com/extensions/content_scripts#run_time因此内容脚本在 onUpdated 报告时已经运行changeInfo.url:

  "content_scripts": [{
    "matches": ["<all_urls>"],
    "js": ["content.js"],
    "run_at": "document_start"
  }],

另一种解决方案是反转通信方向,让内容脚本调用 sendMessage,而后台脚本将在 onMessage 中返回数据,请参阅消息传递 https://developer.chrome.com/extensions/messaging.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

内容脚本未从后台脚本接收消息 (Mv3) 的相关文章