Last active
March 30, 2021 13:20
-
-
Save souljorje/89c6c3bfcad5886f2e3f4d4bcecb39e8 to your computer and use it in GitHub Desktop.
Confirmation for following external links
This file contains hidden or 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
const baseUrl = window.location.origin; | |
const absoluteUrlRegex = new RegExp('^(?:[a-z]+:)?//', 'i'); | |
const isAbsoluteUrl = (url) => absoluteUrlRegex.test(url); | |
const isLocalUrl = (url) => url.startsWith(baseUrl) || !isAbsoluteUrl(url); | |
// https://gist.github.com/ -> github.com | |
const getDomain = (url) => { | |
const urlInstance = new URL(url); | |
const dividedUrl = urlInstance.hostname.split('.'); | |
const urlDomainsCount = dividedUrl.length; | |
return urlDomainsCount === 2 | |
? urlInstance.hostname | |
: `${dividedUrl[urlDomainsCount - 2]}.${dividedUrl[urlDomainsCount - 1]}`; | |
}; | |
const whitelist = [ | |
'twitter.com', | |
'github.com', | |
'stackoverflow.com', | |
'facebook.com', | |
'instagram.com', | |
]; | |
const isWhitelistedUrl = (url) => { | |
const domain = getDomain(url); | |
return domain === window.location.hostname || whitelist.includes(domain); | |
}; | |
// bind listener | |
const confirmExternalLinks = (confirmationFn) => { | |
document.addEventListener('click', async (e) => { | |
const linkElement = e.target.closest('a'); | |
if (!linkElement) return; | |
const link = linkElement.getAttribute('href'); | |
if (isLocalUrl(link) || isWhitelistedUrl(link)) return; | |
e.preventDefault(); | |
const confirmation = await confirmationFn(link); | |
if (confirmation) window.open(link); | |
}); | |
}; | |
// replace confirmationFn with your custom handler which returns Promise | |
confirmExternalLinks((link) => confirm(`Proceed to ${link}?`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment