| 32 | } |
| 33 | |
| 34 | export async function watchForPageUnload (timeout = 500) { |
| 35 | let unloadCallback |
| 36 | const unloadPromise = new Promise((resolve, reject) => { |
| 37 | unloadCallback = () => reject('unload') // eslint-disable-line prefer-promise-reject-errors |
| 38 | window.addEventListener('beforeunload', unloadCallback) |
| 39 | }) |
| 40 | |
| 41 | const timeoutPromise = new Promise((resolve) => setTimeout(resolve, timeout)) |
| 42 | |
| 43 | try { |
| 44 | await Promise.race([unloadPromise, timeoutPromise]) |
| 45 | } finally { |
| 46 | window.removeEventListener('beforeunload', unloadCallback) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Monitors the page for unload events for a specified timeout after calling the supplied function. |