Chrome extension: getBackgroundPage () only fails occasionally

I'm developing a Chrome extension and the following code only throws an error sometimes, not always. In most cases this extension works fine, but sometimes it fails getBackgroundPage () and ends up in the "else" section.

In popup.js

  var bg = chrome.extension.getBackgroundPage();
  if (bg) {
    bg.some_function();
  } else {
    this.updateStatus("Browser error. But you don't have to reload the page to fix it. Just switch to any other browser tab and return to fix.");
  }

      

The background page is handled by eventPage.js

manifest.json

"background": {
  "scripts": ["eventPage.js","jquery-2.1.1.min.js"],
  "persistent": false
},

      

This extension works as a CMS helper tool and provides advanced "find and replace" functionality. It tends to fail when the user is editing a lot of form text on the page. And this can be solved by either reloading the page or navigating to any other tab and then returning to the tab.

What happens when popup.js doesn't get getBackgroundPage ()?
and is there a workaround to avoid the problem?

Thank you very much for your understanding!

+3


source to share


1 answer


You are probably using the Event Page , i.e. "persistent" : false

in the manifest. If it is missing, it is unloaded by Chrome.

The docs indicate what chrome.extension.getBackgroundPage()

might fail in this case, since it is a synchronous method and if the event page is unloaded there is nothing to return immediately.



To get around this, you must use chrome.runtime.getBackgroundPage(callback)

. It is asynchronous and able to wait for the background page to "unfold" for the request.

In general, consider an chrome.extension

API mostly (but not entirely) deprecated in favor of a generic API runtime

.

+1


source







All Articles