Skip to content

Instantly share code, notes, and snippets.

@philbirnie
Last active September 20, 2016 03:11
Show Gist options
  • Save philbirnie/7d042c720c62a78577b1 to your computer and use it in GitHub Desktop.
Save philbirnie/7d042c720c62a78577b1 to your computer and use it in GitHub Desktop.
External Link Prompter
(function() {
/**
* Wrapper Element
* @type {Element}
*/
const wrapperElement = document.querySelector('body');
/**
* Root Domain
* @type {string} rootDomain
*/
const rootDomain = window.location.hostname;
const checkExternalLink = (event) => {
/**
* Event Target
* @type {Node}
*/
let target = event.target;
let external, parent;
if (target.nodeName !== 'A') {
/**
* @type {HTMLElement} HTML Element
*/
parent = target.parentNode;
/**
* Check to make sure that Parent does not equal wrapperElement,
* does not equal parent element (this means it was found) and is not null
* (a catch all to make sure that we don't get into an infinite loop)
*/
while (parent !== wrapperElement && target !== parent && parent !== null) {
if (parent.nodeName === 'A') {
target = parent;
} else {
parent = parent.parentNode;
}
}
}
/**
* Ensure target is a link
*/
if (target.nodeName === 'A') {
/**
* Check that href exists, links is not relative and root is not in domain; if all pass, link is external.
* @type {boolean}
*/
external = target.href !== '' && target.href.indexOf('/') !== 0 && target.href.indexOf(rootDomain) < 0;
if (external) {
if (!window.confirm("You are about to leave the website. Do you wish to continue?")) {
/**
* User clicked "Cancel"; Prevent event action but allow propagation to continue in
* case other listeners exist!
*/
event.preventDefault();
}
}
}
};
/**
* Bind click event to wrapper element.
*/
if (wrapperElement) {
wrapperElement.addEventListener('click', checkExternalLink);
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment