Error in event handler: ReferenceError: window is not defined chrome extension with manifest v3 [duplicate]
Asked Answered
A

3

12

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 ;

Adda answered 30/6, 2021 at 11:43 Comment(2)
ManifestV3 extension uses a service worker so it doesn't have DOM or window. Why do you need window.width in the background script?Hypnotherapy
@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 widthAdda
H
11

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

Hypnotherapy answered 30/6, 2021 at 12:24 Comment(2)
i'd like to get a global function in background by name using window["funcname"] but no window objectRadiophotograph
See Using `window` globals in ManifestV3 service worker background scriptHypnotherapy
F
7

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

Footpace answered 27/7, 2022 at 8:26 Comment(2)
No. I don't think this is window object, but rather self=this=chrome service workerPlatform
yes you are rightFootpace
D
3

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.

Derian answered 28/8, 2021 at 20:20 Comment(1)
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.Hypnotherapy

© 2022 - 2024 — McMap. All rights reserved.