-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add support for back/forward interception (#92)
- Loading branch information
Showing
5 changed files
with
65 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
const interceptors = new Set() | ||
|
||
export const defaultPrompt = 'Are you sure you want to leave this page?' | ||
|
||
let hasIntercepted = false | ||
let hasUserCancelled = false | ||
|
||
export function shouldCancelNavigation() { | ||
if (hasIntercepted) return hasUserCancelled | ||
// confirm if any interceptors return true | ||
return Array.from(interceptors).some(interceptor => { | ||
const prompt = interceptor() | ||
if (!prompt) return false | ||
// cancel navigation if user declines | ||
hasUserCancelled = !window.confirm(prompt) // eslint-disable-line no-alert | ||
// track user response so that multiple interceptors don't prompt | ||
hasIntercepted = true | ||
// reset so that future navigation attempts are prompted | ||
setTimeout(() => { | ||
hasIntercepted = false | ||
hasUserCancelled = false | ||
}, 5) | ||
return hasUserCancelled | ||
}) | ||
} | ||
|
||
export function addInterceptor(handler) { | ||
window.addEventListener('beforeunload', handler) | ||
interceptors.add(handler) | ||
} | ||
|
||
export function removeInterceptor(handler) { | ||
window.removeEventListener('beforeunload', handler) | ||
interceptors.delete(handler) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters