Using ES6 modules in background scripts

(rugk) #1

I looked how one may use a background script es a new ES6 module. However, it seems to be very hard to easily do this.

Usually you embed it like this.

“background”: {
 “script”: [ “background.js” ]

However, with a ES6 module, this does not seem to work, because usually (e.g. when you embed it in a HTML you have to ad the attribute type="module". In a manifest.json this does not seem possible…

So the problem has been discussed in this article and there a simple workaround has been suggested:
Just include a HTML file instead of (only) a JS file in the manifest.json:

“background”: {
 “page”: “background.html”

However, this is of course not very nice and still a workaround.

  • If nobody else comes up with some idea, I guess it is not implemented in Firefox. I’d open a Bugzilla issue then.
  • Also, as for current actions, it should be documented on MDN, that this is not really possible. (and maybe document the workaround)

Using imports
(Martin Giger) #2

There is at the very least an issue open to allow loading es modules as content scripts, since that is not possible with current manifest declarations. And would for sure have higher priority than adding the API for the background page. At the same time I assume adding it for the background page will be much easier once it’s possible for content scripts.

Currently mdn does not document at all how es modules behave, though the knowledgeable programmer would be aware that es modules require a special loading mode and thus hopefully realize that they need to load their scripts with type=“module” (which by no means is a work around).

Edit: just stumbled across the bug requesting the very thing for the bg page:

(rugk) #3

Hu?`Actually background pages do work. At least syntactically Firefox accepts them (JS itself still needs some testing) and the (already linked) MDN doc does not mention any such limitation.

(Martin Giger) #4

You are right, it would be mainly a matter of adding a key that triggers a different bg page template (though the properties would have to be mutually exclusive, which is fun) and it involves some C++ nonetheless.

Yet, the fact that you can already use modules with the bg page should, in my eyes, make work to add a shortcut less important than supporting them for content scripts.

(rugk) #5

Okay, so good to hear the workaround works. And sure, it is then less a priority, but would still be good. Because that background page is very obviously a workaround and thus no proper solution for this use case.