Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...