Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - Why is chrome.runtime undefined in the content script?

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.

Background Script:

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

Content Script:

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

Other Info:

  • Chrome Version 58.0.3029.110 (64-bit)
  • Installing my extension as an "Unpacked extension" with developer mode
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...