Search code examples
google-chrome-extensionservice-workerchrome-extension-manifest-v3web-extension

Background page runs, but popup says 'You do not have a background page.' when using getBackgroundPage()


I have a very simple background page for a Chrome extension:

chrome.runtime.onInstalled.addListener((reason) => {
  console.log(reason);
});

The background page runs when my extension is loaded: enter image description here

The extension also has a popup that runs getBackgroundPage(), using:

const serviceWorkerWindow = await chrome.runtime.getBackgroundPage();

This fails with:

Uncaught (in promise) Error: You do not have a background page.

How do I make getBackgroundPage() work?


Solution

  • Answering my own question based on @wOxxOm's comment. If wOxxOm writes their own answer I'll mark that as correct.

    My expectation based on Google's documentation was that getBackgroundPage():

    retrieves the JavaScript 'window' object for the background page running inside the current extension/app.

    In modern JS terms, this would be the globalThis for the service worker (the service workers is still referred to as background in manifest v3.

    As wOxxOm said.

    This API won't work. The documentation is simply outdated because the ManifestV3 team consists of just a few devs who don't have time to do everything.

    Essentially the Chrome Extension documentation is not adequately maintained. There is an outstanding W3C issue on the topic of whether getBackgroundPage should work with service workers - thanks @erosman. The best way to communicate between a popup and a background service worker is via extension messaging. Ie:

    chrome.runtime.sendMessage()
    

    And:

    chrome.runtime.onMessage.addListener()