Error in event handler: ReferenceError: window is not defined chrome extension with manifest v3

Viewed 7453

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 ;

3 Answers

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.

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

Related