Chrome Extensions - How to check if its a specific page ( Popup, Options, Devtools, Background, ContentScript )?

40 Views Asked by At

I am working on a library which needs to be called & executed in the background script only. How to check if the library is being executed in background script only ?

  • So, something like this :..
const isBackgroundScript = checkForBackgroundScript();
if (!isBackgroundScript) {
   throw new Error(`xyz function can only be called from background script`); 
}
1

There are 1 best solutions below

0
wOxxOm On BEST ANSWER

ManifestV3 background script is a service worker:

const isBackgroundScript = typeof ServiceWorkerGlobalScope === 'function';

ManifestV2:

const isBackgroundScript = chrome.extension.getBackgroundPage() === window;