Search code examples
javascriptgoogle-chrome-extensionfirefox-addon-webextensionswebextension-polyfill

Accessing variables in browser.runtime.getBackgroundPage()


I'm currently building a browser extension with create-react-app as the base, trying to use getBackgroundPage() instead of the messaging API to communicate between the background scripts (I have 3 defined) and the new tab page, but it seems like calling browser.runtime.getBackgroundPage() in the new tab page returns a Window object without any of my functions or variables from the background scripts attached as Window properties.

The below returns a "variable not defined" error and "page.foo() is not a function".

// background_3.js

var test = [];

// Some stuff so webpack doesn't get rid of the unused variable.
for (let i = 0; i < 10; ++i) {
    test.push(i);
}

function foo() {
    console.log("foo");
}
// New Tab React page
import browser from "webextension-polyfill";

browser.runtime.getBackgroundPage()
    .then(page => {
        console.log(page.test);
        page.foo();
    });

Is there something I'm doing wrong? Should I just use the message API instead?


Solution

  • Turns out webpack is wrapping my background scripts inside some other functions which is what's breaking things. You can manually attach things to the window object in the background script by just doing window.foo = foo like how wOxxOm suggested.