fetch-event-source icon indicating copy to clipboard operation
fetch-event-source copied to clipboard

Error: document is not defined

Open rendomnet opened this issue 2 years ago • 9 comments
trafficstars

I'm trying to use this library in browser extension service worker. And it gives me error "document is not defined".

rendomnet avatar Apr 20 '23 04:04 rendomnet

me too

zhl5213 avatar May 10 '23 07:05 zhl5213

me too

yaxiaoliu avatar May 19 '23 15:05 yaxiaoliu

me too

jeromewe avatar Jun 29 '23 09:06 jeromewe

me too i set openWhenHidden to true then this error disappeared but "window is not defined" occured

i saw source codes contained document and window object

May I know if browser extension service worker is supported? Thank you.

luichooy avatar Jul 13 '23 11:07 luichooy

It works fine by:

  1. Set openWhenHidden to true.
  2. Mock a window constant.
if (!globalThis.window) {
  globalThis.window = {
    fetch: globalThis.fetch,
    setTimeout: globalThis.setTimeout,
    clearTimeout: globalThis.clearTimeout,
  }
}

imrockpan avatar Jul 20 '23 02:07 imrockpan

if (!globalThis.window) {
  globalThis.window = {
    fetch: globalThis.fetch,
    setTimeout: globalThis.setTimeout,
    clearTimeout: globalThis.clearTimeout,
  }
}

to make it more robust:

if (!globalThis.window) {
  globalThis.window = {
    fetch: globalThis.fetch,
    setTimeout: (fn, timeout) => globalThis.setTimeout(fn, timeout),
    clearTimeout: (t) => globalThis.clearTimeout(t),
  };
}
if (!globalThis.document)
  globalThis.document = { removeEventListener: () => {} };

pond918 avatar Jul 26 '23 08:07 pond918

me too

Any updates?

HereOrCode avatar Jan 31 '24 14:01 HereOrCode

I am trying to use it in Next.js 14's app handler and can face this issue since the code is running on the server, which is Node.js. But I wonder why fetch-event-source needs to read the document.

LikeDreamwalker avatar Jul 15 '24 06:07 LikeDreamwalker

Same error here ! but when I add the fix above, then when I refresh the page I got a TypeError: Cannot destructure property 'protocol' of 'window.location' as it is undefined.

I am going mad...

CharlesOural avatar Aug 21 '24 18:08 CharlesOural