Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
19 changes: 11 additions & 8 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand All @@ -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, {
Expand Down Expand Up @@ -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();
Expand Down