为什么chrome.runtime在内容脚本中未定义?

Tyl*_*coe 7 javascript google-chrome-extension

我有一个非常简单的chrome扩展,我正在尝试将消息从后台脚本传递到内容脚本.但是chrome.runtime未定义.

这里几乎是所有的代码,你可以看到几乎没有任何代码.在内容脚本中,运行时未定义.

后台脚本:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.runtime.sendMessage({action: 'someAction'}, 
    function(response) {
      console.log('Response: ', response);
    });
});
Run Code Online (Sandbox Code Playgroud)

内容脚本:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  sendResponse({
    user: 'user'
  });
});
Run Code Online (Sandbox Code Playgroud)

的manifest.json

{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1.0",

  "description": "Some stupid extension",

  "browser_action": {
    "default_icon": "icons/MyExtensionIcon.png"
  },
  "icons": {
    "48": "icons/MyExtensionIcon.png"
  },
  "permissions": [
    "tabs",
    "storage",
    "https://*/",
    "http://*/"
  ],
  "content_scripts": [
    {
      "matches": ["*://*.twitter.com/*", "https://twitter.com/*"],
      "js": ["js/content.js"]
    }
  ],
  "background": {
    "scripts": ["js/background.js"],
    "persistent": true
  },
  "web_accessible_resources": [
    "js/*",
    "css/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

其他信息:

  • Chrome版本58.0.3029.110(64位)
  • 使用开发人员模式将我的扩展程序安装为"Unpacked extension"

Tyl*_*coe 18

好吧我明白了.这绝对是愚蠢的,但看起来这只是一个Heisenbug.通过添加断点或调试器语句,它会导致该值未定义.也许是一个铬虫?

我发誓,每天Chrome感觉更多,更像是Internet Explorer.

  • 2年后,此错误仍然存​​在,使用chrome 75.0.3735.0 (7认同)
  • 在 Chrome 版本 77.0.3865.120 中仍然遇到此错误,其中打开开发工具会导致 chrome.runtime 未定义,但关闭开发工具在使用 https://developer.chrome.com/extensions/messaging#external-webpage 时工作正常 (2认同)