diff --git a/package.json b/package.json index 90ea2f6..8528735 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@microsoft/fetch-event-source", - "version": "2.0.1", + "version": "2.0.3", "description": "A better API for making Event Source requests, with all the features of fetch()", "homepage": "https://github.com/Azure/fetch-event-source#readme", "repository": "github:Azure/fetch-event-source", diff --git a/src/fetch.ts b/src/fetch.ts index 162ea45..1e2236c 100644 --- a/src/fetch.ts +++ b/src/fetch.ts @@ -74,20 +74,20 @@ export function fetchEventSource(input: RequestInfo, { let curRequestController: AbortController; function onVisibilityChange() { curRequestController.abort(); // close existing request on every visibility change - if (!document.hidden) { + if (!globalThis.document?.hidden) { create(); // page is now visible again, recreate request. } } - if (!openWhenHidden) { - document.addEventListener('visibilitychange', onVisibilityChange); + if (globalThis.document && !openWhenHidden) { + globalThis.document?.addEventListener('visibilitychange', onVisibilityChange); } let retryInterval = DefaultRetryInterval; let retryTimer = 0; function dispose() { - document.removeEventListener('visibilitychange', onVisibilityChange); - window.clearTimeout(retryTimer); + globalThis.document?.removeEventListener('visibilitychange', onVisibilityChange); + globalThis.clearTimeout(retryTimer); curRequestController.abort(); } @@ -97,9 +97,12 @@ export function fetchEventSource(input: RequestInfo, { resolve(); // don't waste time constructing/logging errors }); - const fetch = inputFetch ?? window.fetch; + const fetch = inputFetch ?? globalThis.fetch; const onopen = inputOnOpen ?? defaultOnOpen; async function create() { + if (curRequestController) { + curRequestController.abort(); + } curRequestController = new AbortController(); try { const response = await fetch(input, { @@ -131,8 +134,8 @@ export function fetchEventSource(input: RequestInfo, { try { // check if we need to retry: const interval: any = onerror?.(err) ?? retryInterval; - window.clearTimeout(retryTimer); - retryTimer = window.setTimeout(create, interval); + globalThis.clearTimeout(retryTimer); + retryTimer = globalThis.setTimeout(create, interval); } catch (innerErr) { // we should not retry anymore: dispose();