Skip to content
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

User reports network failure to load Stripe.js fails again after network is restored #518

Merged
merged 10 commits into from
Dec 8, 2023
56 changes: 43 additions & 13 deletions src/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,26 @@ const registerWrapper = (stripe: any, startTime: number): void => {

let stripePromise: Promise<StripeConstructor | null> | null = null;

let onErrorListener: (() => void) | null = null;
let onLoadListener: (() => void) | null = null;

const onError = (reject: (reason?: any) => void) => () => {
reject(new Error('Failed to load Stripe.js'));
};

const onLoad = (
resolve: (
value: StripeConstructor | PromiseLike<StripeConstructor | null> | null
) => void,
reject: (reason?: any) => void
) => () => {
if (window.Stripe) {
resolve(window.Stripe);
} else {
reject(new Error('Stripe.js not available'));
}
};

export const loadScript = (
params: null | LoadParams
): Promise<StripeConstructor | null> => {
Expand Down Expand Up @@ -96,26 +116,36 @@ export const loadScript = (
console.warn(EXISTING_SCRIPT_MESSAGE);
} else if (!script) {
script = injectScript(params);
} else if (
script &&
onLoadListener !== null &&
onErrorListener !== null
) {
// remove event listeners
script.removeEventListener('load', onLoadListener);
script.removeEventListener('error', onErrorListener);

// if script exists, but we are reloading due to an error,
// reload script to trigger 'load' event
script.parentNode?.removeChild(script);
fruchtose-stripe marked this conversation as resolved.
Show resolved Hide resolved
script = injectScript(params);
}

script.addEventListener('load', () => {
if (window.Stripe) {
resolve(window.Stripe);
} else {
reject(new Error('Stripe.js not available'));
}
});

script.addEventListener('error', () => {
reject(new Error('Failed to load Stripe.js'));
});
onLoadListener = onLoad(resolve, reject);
onErrorListener = onError(reject);
script.addEventListener('load', onLoadListener);

script.addEventListener('error', onErrorListener);
} catch (error) {
reject(error);
return;
}
});

return stripePromise;
// Resets stripePromise on error
return stripePromise.catch((error) => {
stripePromise = null;
return Promise.reject(error);
});
};

export const initStripe = (
Expand Down
Loading