Skip to content

Commit

Permalink
User reports network failure to load Stripe.js fails again after netw…
Browse files Browse the repository at this point in the history
…ork is restored (#518)

* fix stripe promise reload

* remove whitespace

* yarn prettier

* don't wrap error in new Error

* pr feedback

* prettier

* remove event listeners

* pr feedback

* add onloadlistener and onerror listener

* add onLoadListener and onErrorListener
  • Loading branch information
maxwelly-stripe committed Dec 8, 2023
1 parent c5ce917 commit 0309bef
Showing 1 changed file with 43 additions and 13 deletions.
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);
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

0 comments on commit 0309bef

Please sign in to comment.