4

I'm currently trying to update my chrome extension with es6 classes. It works fine in the context of the background scripts. But I can't access this classes from within the ui page (i.e. the extension's popup) using chrome.extension.getBackgroundPage().

background.js

function Foo() { ... }
class Bar { ... }

popup.js

var bg = chrome.extension.getBackgroundPage();
new bg.Foo() // works
new bg.Bar() // Bar is undefined

I found this simple workaround:

background.js

class Bar {}
var exports = { Bar : Bar };

popup.js

var bg = chrome.extension.getBackgroundPage();
new bg.exports.Bar() // works

Any ideas why it's not possible to get direct access to classes via the 'bg' object?

char bugs
  • 419
  • 2
  • 8
  • 1
    What does this have to do with ES6 classes? Does it work if you use ES5 `function` syntax? – Bergi Dec 09 '17 at 21:00
  • As the example shows it does. Maybe I made it not clear enough? I changed it a little. Have a look at the code comments: bg.Foo (function syntax) is defined, but bg.Bar (class syntax) isn't. – char bugs Dec 09 '17 at 22:10
  • Oops, I was blind. – Bergi Dec 09 '17 at 22:17

1 Answers1

4

Any ideas why it's not possible to get direct access to classes via the 'bg' object?

Yes: classes do not become properties of the global object even if they are global.

You don't need that exports object for a workaround, you can simply use

var Bar = class { … };
Bergi
  • 630,263
  • 148
  • 957
  • 1,375