Detect that code is running in background script

I’m now sharing modules between different contexts and right now I need to detect whether the module is running in background script.
Is there some official API for that?

1 Like

You want to know what page you’re loaded in or content script vs. add-on script? The latter you can do in a variety of ways, including checking window.location or API presence detection (since content scripts only get a sub set). The former can be done to some extent using the tabs.getCurrent() API.

1 Like

Basically yes, I want to know if I’m loaded in background page.
So I’m looking for a “background script” vs “anything else” (addon page, options page, popup or content script).

Using window.location is a good idea! Using URL from manifest should make this work even across projects:

window.location.href === browser.runtime.getManifest()

You may have to turn it into an actual moz-extension URI using runtime.getURL. Note that this method only works if you actually set a page, and don’t get the default HTML page.

An alternative for the BG page specificly could also be to check if returns your window global or has the same location or similar (not sure if it’s supposed to return the same instance or if it’s a proxy).

What do you mean with browser.runtime.getURL()? It requires file name, I would have to fetch the manifest again.

But the location should be available everywhere, even in Web Workers!

But you are right, it will work only if you have html page for your background script - which is currently required for modules anyway.

Regarding runtime​.get​Background​Page() - it seems to work as well:

window === await browser.runtime.getBackgroundPage()

But it’s asynchronous which may be a complication in some situations.

It’s 2019, asynchronicity with await should not be a problem. :wink: Async rocks! :smiley:

Of course :smiley: , async /await is the best javascript feature. But in this case, if you can use sync. API without performance penalty, then it’s definitely a better way.

Also there are cases where you just can’t use asynchronous code, like during transaction in IndexedDB or with DOM event handlers where you won’t be able to stop propagation after first await and etc…

Actually this works properly only in Firefox, in Chrome browser.runtime.getManifest() returns only relative path, like "background/background.html".

I really hate these path differences that breaks code :frowning:, there should be some standard for that.