首页 > 解决方案 > Chrome 扩展 - “无法读取未定义的属性‘onMessage’”

问题描述

创建 Chrome 扩展程序。

扩展的一部分是获取当前选项卡 URL。

我发现这样做的唯一方法是将脚本放入background.js并在其中设置一个事件侦听器script.js

除了这就是我的想法......我一直在谷歌,StackOverflow,显然一切都指向相同的答案,将脚本放入background.js并有一个事件监听器,script.js但我不断得到Cannot read property 'onMessage' of undefined

下面的代码不起作用,因为它获取的是 Chrome ext url,而不是当前的 tab url

current_url = window.location.href
console.log(current_url)

以下是我目前拥有的:

背景.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "from a content script:" + sender.tab.url :
                    "from the extension");
        if (request.greeting === "hello")
        sendResponse({farewell: "goodbye"});
    }
    ); 

脚本.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "from a content script:" + sender.tab.url :
                    "from the extension");
        if (request.greeting === "hello")
        sendResponse({farewell: "goodbye"});
    }
    ); 

manifest.js

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting", "bookmarks", "tabs"],
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
  },
  "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  },
  "options_page": "options.html"
}

标签: javascriptgoogle-chromegoogle-chrome-extension

解决方案


推荐阅读