Why does chrome.extension.getBackgroundPage() return null?

I have a manifest.json file that looks like this:

{
  "name": "Zend Debugger Extension",
  "version": "0.1",
  "background_page": "background.html",
  "permissions": [
    "cookies", "tabs", "http://*/*", "https://*/*"
  ],
  "browser_action": {
    "default_title": "Launch Zend Debugger",
    "default_icon": "icon.png",
    "popup": "popup.html"
  }
}

Here's my background.html :

<html>
    <script>
    function testRequest() {
        console.log("test Request received");
    }
    </script>
</html>

And my popup.html :

<script>
function debug(target) {
    if (target.id == 'thisPage') {
        console.log('sending request');
        chrome.extension.getBackgroundPage().testRequest();
    }
}
</script>

<div onclick="debug(this)" id="thisPage">Current Page</div>

However, the background.html page doesn't seem to be accessible. I'm getting this error:

Uncaught TypeError: Cannot call method 'testRequest' of null

When I inspect chrome.extension.getBackgroundPage() I get a null value. I'm thinking I have made a mistake in my manifest file, but I can't see what I've done wrong.

Thanks.


You are missing the background permission, take a look at my manifest.json file of my chrome extension:

{
    "content_scripts": [
    {
      "matches": ["http://*/*"],
      "js": ["jquery.js", "asserts.js"]
    }
  ],
  "name": "Test Extension",
  "version": "1.0",
  "description": "A test extension to inject js to a webpage.",
  "background_page": "background.html",
  "options_page": "options.html",
  "browser_action": {
    "default_icon": "icon.png",
    "popup": "popup.html"
  },
  "permissions": [
    "tabs", 
    "http://*/*", "https://*/*", "<all_url>", "background"
  ]
}

EDIT: Are you sure you have the background.html file on the same folder as all your chrome-extension's files?, and if so, try reloading your extension from the extension management page, I remember once had a bug that my extension didn't reload, so I went to the developer's tools for my background page and executed window.location.reload(true); from console, that fixed it. Please respond if this worked, I will keep researching


Here's another answer with more options:

chrome.extension.getBackgroundPage() returns null after awhile

According to the referenced page (Difference between Event and Background Page) there is a better option to get the background while still using Event Page :

If your extension uses, extension.getBackgroundPage, switch to runtime.getBackgroundPage instead. The newer method is asynchronous so that it can start the event page if necessary before returning it.

链接地址: http://www.djcxy.com/p/55830.html

上一篇: 通过编程切换Android配置文件

下一篇: 为什么chrome.extension.getBackgroundPage()返回null?