|
| 1 | +const BROADCAST_CHANNEL = "redirect_callback"; |
| 2 | +export const REDIRECT_CALLBACK_PATH = "/callback"; |
| 3 | + |
| 4 | +export class PopupClosedError extends Error {} |
| 5 | + |
| 6 | +export const redirectInPopup = (url: string): Promise<string> => { |
| 7 | + const width = 500; |
| 8 | + const height = 600; |
| 9 | + const left = (window.innerWidth - width) / 2 + window.screenX; |
| 10 | + const top = (window.innerHeight - height) / 2 + window.screenY; |
| 11 | + const redirectWindow = window.open( |
| 12 | + url, |
| 13 | + "_blank", |
| 14 | + `width=${width},height=${height},left=${left},top=${top}`, |
| 15 | + ); |
| 16 | + |
| 17 | + return new Promise<string>((resolve, reject) => { |
| 18 | + // We need to throw an error when the window is closed, else the page and |
| 19 | + // thus the user will wait indefinitely for a result that never comes. |
| 20 | + // |
| 21 | + // We can't listen to close events since the window is likely cross-origin, |
| 22 | + // so instead we periodically check the closed attribute with an interval. |
| 23 | + const closeInterval = setInterval(() => { |
| 24 | + if (redirectWindow?.closed === true) { |
| 25 | + clearInterval(closeInterval); |
| 26 | + reject(new PopupClosedError()); |
| 27 | + } |
| 28 | + }, 500); |
| 29 | + // Listen to the popup, we expect a message with the url of the callback, |
| 30 | + // after receiving it we can close the popup and resolve the promise. |
| 31 | + const channel = new BroadcastChannel(BROADCAST_CHANNEL); |
| 32 | + channel.addEventListener("message", (event) => { |
| 33 | + if (typeof event.data !== "string") { |
| 34 | + return; |
| 35 | + } |
| 36 | + channel.close(); |
| 37 | + redirectWindow?.close(); |
| 38 | + window.focus(); |
| 39 | + resolve(event.data); |
| 40 | + }); |
| 41 | + }); |
| 42 | +}; |
| 43 | + |
| 44 | +export const sendUrlToOpener = (): void => { |
| 45 | + const channel = new BroadcastChannel(BROADCAST_CHANNEL); |
| 46 | + channel.postMessage(window.location.href); |
| 47 | + channel.close(); |
| 48 | +}; |
0 commit comments