【问题标题】:Google Chrome extension Content Script doesn't work谷歌浏览器扩展内容脚本不起作用
【发布时间】:2020-03-10 21:36:41
【问题描述】:

我已尝试应用与内容脚本问题相关的其他主题的解决方案,但它们不起作用。 开发工具中的源代码看不到来自该扩展的内容脚本。 我从扩展控制台收到错误

未经检查的 runtime.lastError:无法建立连接。接收端不存在。

看起来扩展根本看不到 content.js。

所以,我的情况 - content.js 没有响应和工作。我是否错过了 manifest.json 中的某些内容?

ma​​nifest.json

    "name": "Notification Extension",
    "version": "1.0",
    "description": "Build an Extension!",
    "permissions": [
        "storage",
        "notifications",
        "alarms",
        "activeTab",
        "tabs",
        "http://*/*",
        "https://*/*"
    ],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "browser_action": {
      "default_popup": "popup.html"
    },
    "content_scripts": [
      {
        "matches": [
          "http://*/*",
          "https://*/*"
        ],
        "js": ["content.js"],
        "run_at": "document_end"
      }
    ],
    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
    "manifest_version": 2
  }

content.js

console.log('content.js is working');

chrome.runtime.onMessage.addListener(
    (request, sender, sendResponse) => {
        if(request.createAlarm){

            console.log('alarm senedet to content.js')
        }
    }
)

popup.js

chrome.tabs.query({active:true, currentWindow:true}, (tabs) => {
    chrome.tabs.sendMessage(tabs[0].id, {createAlarm: true, message: 'sending to extension'}, (response) => {
        console.log('message arrived');
    })
})

感谢您的帮助!

【问题讨论】:

  • 错误消息 syas 没有在该选项卡中运行内容脚本,因此它是 chrome:// 选项卡,或者您需要在重新加载或重新启用扩展程序后 reinject content scripts explicitly。否则,您必须手动重新加载选项卡才能让 Chrome 运行内容脚本。

标签: javascript google-chrome-extension


【解决方案1】:

我相信你只能使用chrome.tabs.sendMessage将消息从后台脚本发送到内容脚本。

检查此答案以获得有效的解决方案: https://stackoverflow.com/a/47313968/3862289

【讨论】:

  • 感谢您的重播。据我所知,可以在所有扩展部分之间发送消息(关于developer.chrome.com/extensions/messaging)。但尽管如此,来自 content.js 的 console.log 不会在网站控制台中记录任何内容。所以看起来扩展没有看到 content.js。我认为这可能与我的清单有关,但我什么都看不到。
  • 哦,所以您的内容脚本根本没有运行?那么问题实际上与消息传递无关(我认为您也必须修复该部分)。你没有说你在哪个 URL 上尝试了这个,认为应该根据 developer.chrome.com/extensions/match_patterns 匹配所有内容。你能告诉我们你在哪个 URL 上尝试过这个吗?您可以尝试改用 吗?
【解决方案2】:

所以,最后的问题是我试图测试扩展的“新卡”。它应该是任何网站。 我的错。但我要感谢你的帮助! 对不起,打扰了。 最好的问候!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    相关资源
    最近更新 更多