9

I am using manifest version 3 for chrome extension this error I face in background js : Error in event handler: ReferenceError: window is not defined chrome extension with manifest v3

"manifest_version":3, "permissions":["contextMenus","storage", "activeTab","tabs","scripting","webRequest"],

var posLeft = ( window.width - winWidth ) / 2 ;

Hemant Pawar
  • 360
  • 1
  • 3
  • 14
Mitul Sabhaya
  • 93
  • 1
  • 1
  • 5
  • 1
    ManifestV3 extension uses a service worker so it doesn't have DOM or `window`. Why do you need window.width in the background script? – wOxxOm Jun 30 '21 at 11:49
  • 1
    @wOxxOm I want to set chrome.windows.create open in center in browser screen, So first i want to get window.width then I minus chrome.windows width – Mitul Sabhaya Jun 30 '21 at 11:58

3 Answers3

7

ManifestV3 extension uses a service worker so it doesn't have DOM or window.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • i'd like to get a global function in background by name using `window["funcname"]` but no window object – Dee Apr 05 '23 at 14:51
  • 2
    See [Using \`window\` globals in ManifestV3 service worker background script](https://stackoverflow.com/a/73785852) – wOxxOm Apr 05 '23 at 17:45
3

If you are trying to access window object in background.js as it is a service worker you won't have access to window object , but you may try self as it will have all the properties of window object in background.js try

console.log(self,"self")
var window = window ?? self;

Note: if you are using Vite or Webpack this might work

enter image description here

Goutham J.M
  • 1,726
  • 12
  • 25
2

Well for others who may look here for that error message in a similar context, I got the same error when neglecting to make the window object accessible at runtime rather than at the time that the injected function is dynamically being readied for injection into a particular tab by the v3 background script.

In order to get dynamically injected from a v3 background script, the tab specific object (in this case window) needs to be included inside the function being passed, as in the following anonymous function case:

chrome.scripting.executeScript({
    target: { tabId: currentTab.id },
    func: () => window.history.back()
  }); 

if window.history.back is provided as the value for func then obviously it will not be known or available to the background script and the same error message will ensue.

This is already described indeed in the docs.

matanster
  • 15,072
  • 19
  • 88
  • 167
  • 3
    FWIW, this code works in ManifestV3 service worker because the function never runs in the context of the service worker, it is serialized as a string, which get injected into the tab. – wOxxOm Aug 28 '21 at 20:28