46 lines
1.3 KiB
JavaScript
46 lines
1.3 KiB
JavaScript
(() => {
|
|
const redirectPath = '/go/';
|
|
const urlParams = new URLSearchParams(window.location.search);
|
|
|
|
if (window.location.pathname === redirectPath || window.location.pathname === '/go') return;
|
|
if (urlParams.get('noExternalRedirect') === '1') return;
|
|
|
|
function getExternalUrl(anchor) {
|
|
const href = anchor.getAttribute('href');
|
|
if (!href || href.startsWith('#')) return null;
|
|
|
|
let targetUrl;
|
|
try {
|
|
targetUrl = new URL(href, window.location.href);
|
|
} catch {
|
|
return null;
|
|
}
|
|
|
|
if (!['http:', 'https:'].includes(targetUrl.protocol)) return null;
|
|
if (targetUrl.origin === window.location.origin) return null;
|
|
|
|
return targetUrl.href;
|
|
}
|
|
|
|
document.addEventListener('click', (event) => {
|
|
const anchor = event.target.closest?.('a[href]');
|
|
if (!anchor) return;
|
|
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
|
|
|
|
const externalUrl = getExternalUrl(anchor);
|
|
if (!externalUrl) return;
|
|
|
|
event.preventDefault();
|
|
|
|
const redirectUrl = `${redirectPath}?url=${encodeURIComponent(externalUrl)}`;
|
|
const target = anchor.getAttribute('target');
|
|
|
|
if (target && target !== '_self') {
|
|
window.open(redirectUrl, target, 'noopener,noreferrer');
|
|
return;
|
|
}
|
|
|
|
window.location.href = redirectUrl;
|
|
});
|
|
})();
|