Search code examples
google-chrome-extensionchrome-extension-manifest-v3web-extension

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


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`); 
}

Solution

  • ManifestV3 background script is a service worker:

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

    ManifestV2:

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