Using `window` globals in ManifestV3 service worker background script
R

1

5

I'm working on a Manifest v3 browser extension where I need to identify the browser in which the extension is currently running from the backgroundScript. Since ManifestV3 extension uses a service worker, it doesn't have DOM or window. So I'm not able to use window.navigator.userAgent.

I found a related question which talks about how to gets window height and width information, but I couldn't find any other information to fetch the userAgent of the browser.

Is this possible?

Raggletaggle answered 19/9, 2022 at 19:6 Comment(3)
Get the navigator object from a content script and send that to the service worker with sendMessage or you could use getPlatformInfo in a service worker event if you think that could work for youDorolice
you can use both navigator.userAgent or navigator.userAgentData.brands. Better the 2nd 'cause the 1st is going to be depracated.Macnamara
Thank you @wOxxOm, thank worked. Can you add that as an answer?Raggletaggle
G
7

Neutral globals

Things like navigator aren't specific to visual representation of a window.
Just omit window. and read it directly:

  • navigator
  • navigator.userAgent
  • atob
  • fetch

Window-specific globals

Things specific to user interaction or visual/aural representation like DOM or AudioContext, or those that may show a prompt for user permissions.

Not available in a worker. The workaround is to split that part of the code into the offscreen document and use messaging to pass the data back and forth. It can be chrome.runtime messaging or navigator.serviceWorker messaging, which supports binary data like Uint8Array, Blob, Map, etc.

Aliases for window

Use them instead of window for code clarity or if a local variable is named just as a global property.

  • Built-in globalThis (Chrome/ium 71+, FF 65+) and self

    These are worker-compatible aliases for the global scope. Note that a JS library you're loading may redefine them theoretically, but that'd be really weird and abnormal.

  • Self-made global

    The most reliable method, but you'll have to add 'use strict' only inside an IIFE not globally.
    This is already offered by bundlers like webpack.
    Here's how you can replicate it yourself:

    const global = (function(){
      if (!this) throw "Don't add 'use strict' globally, use it inside IIFE/functions";
      return this;
    })();
    
Gaffrigged answered 20/9, 2022 at 11:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.