Skip to content

Pr/make web worker friendly #8

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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",
19 changes: 11 additions & 8 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -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();