Skip to content

Instantly share code, notes, and snippets.

@cedeber
Created April 3, 2018 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cedeber/9a104d055f7cb7edf144cabcfad0f8f9 to your computer and use it in GitHub Desktop.
Save cedeber/9a104d055f7cb7edf144cabcfad0f8f9 to your computer and use it in GitHub Desktop.
Apply before page exits
function applyBeforeExit(doBefore) {
document.addEventListener("click", async (event) => {
// Test for left click.
if (event.button !== 0) {
return;
}
let element = event.target;
// Go up through the DOM tree to search for a link
while (element && !element.hasAttribute("href")) {
element = element.parentElement;
}
if (element) {
const location = element.getAttribute("href");
// If the link is for e-mail, phone or new window, do nothing
if ((location && /^((mailto|tel):|#)/.test(location)) || element.hasAttribute("target")) {
return;
}
event.preventDefault();
try {
await doBefore();
} catch (_e) { /* empty */ }
// Once callback returns a promise, go to the new page
if (location) {
window.location.assign(location);
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment