1

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?

  • It should work as written. The only explanation for the error is that you've actually used lexically scoped declarations such as `const` or `let` instead of `var` and a global function. Or maybe your bundler/compiler wraps the background script code in IIFE/whatever. – wOxxOm Jun 09 '19 at 03:33
  • I'm using `create-react-app` as my base. Just took a look at the script inside of the build output and it looks like it's being wrapped in another function. Anything I can do without doing `npm eject` to pull out the things or am I out of luck here? –  Jun 09 '19 at 03:37
  • You can manually expose stuff like `window.foo = foo` and so on. – wOxxOm Jun 09 '19 at 03:40
  • Looks like that worked. Thank you! –  Jun 09 '19 at 03:43

1 Answers1

2

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.