外链跳转

This commit is contained in:
2026-06-18 18:42:26 +08:00 Unverified
parent b066a94ce3
commit 41854a128d
5 changed files with 346 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
(() => {
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;
});
})();