Created
April 3, 2018 16:57
-
-
Save cedeber/9a104d055f7cb7edf144cabcfad0f8f9 to your computer and use it in GitHub Desktop.
Apply before page exits
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
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