为什么 chrome.runtime 在内容脚本中未定义? [英] Why is chrome.runtime undefined in the content script?

查看:80
本文介绍了为什么 chrome.runtime 在内容脚本中未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a very simple chrome extension, where I'm trying to pass a message from the background script to the content script. But chrome.runtime is undefined.

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

Here's literally all the code, as you can see there's almost nothing to it. In the content script, runtime is undefined.

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

内容脚本:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  sendResponse({
    user: 'user'
  });
});

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/*"
  ]
}

其他信息:

  • Chrome 版本 58.0.3029.110(64 位)
  • 将我的扩展安装为开发者模式下的解压扩展"

推荐答案

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

Ok I figured it out. It's absolutely stupid, but it appears this is simply a Heisenbug. By adding a breakpoint, or debugger statement, it causes that value to be undefined. Maybe a chrome bug?

我发誓,Chrome 每天都感觉越来越像 Internet Explorer.

I swear, every day Chrome feels more, and more like Internet Explorer.

这篇关于为什么 chrome.runtime 在内容脚本中未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆