-
网站禁止js跳转非本站域名代码
1、下载文件后解压到本地,其中包含一个js文件夹和放跳转的js文件,按照自己的需求上传到服务器。 如果你的网站根目录有js文件夹,那么直接把里面的js文件上传到js文件夹里,如果根目录没有js文件夹,那么连同js文件夹一起上传到网站根目录。 2、打开并编辑js文件,把白名单域名改成自己的域名,建议填www网址和手机版网址,如果不需要,把下面两行删除,//当前域名前的逗号也删除。 3、把这段js代码引入网站模板,一般是在head.html或include.html文件里,找到</script>标签,把这段代码放在</script>最上面,一定要让这个js文件最先加载,它才能有效拦截跳转。 代码全部: // 设置允许的域名白名单(包括主域名及其子域名) const allowedDomains = [ location.hostname, // 当前域名 'aaa', // 其他可信域名 'bbb', 'ccc'// 子域名 ]; // 监听所有链接点击事件 document.addEventListener('click', function(event) { // 向上查找最近的<a>标签 let target = event.target; while (target && target.tagName !== 'A') { target = target.parentElement; if (!target) return; } const href = target.getAttribute('href'); // 只处理带有href属性的链接 if (!href || href.startsWith('javascript:')) return; try { // 解析完整URL const url = new URL(href, document.baseURI); // 检查域名是否在允许列表 const isAllowed = allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain) ); // 阻止非允许域名的跳转 if (!isAllowed) { event.preventDefault(); console.warn('禁止跳转到外部域名:', url.hostname); alert('为了您的安全,已阻止跳转到外部网站'); // 这里可以替换为自定义处理逻辑 } } catch (e) { // 处理无效URL console.error('链接解析错误:', e); } }); // 防止通过修改location跳转 const originalLocation = window.location; Object.defineProperty(window, 'location', { get: () => originalLocation, set: value => { try { const url = new URL(value, document.baseURI); if (!allowedDomains.some(d => url.hostname.endsWith(d))) { console.warn('已阻止location跳转到:', url.hostname); return; } } catch(e) {} originalLocation.href = value; }, configurable: false }); 或前往文章来源处下载文件获取。 根据原作者的内容我改了一份可以拦截window.open的版本,理论上会更强大。 完整代码(anti-redirect.js): (function () { var _original = { open: window.open, assign: window.location.assign.bind(window.location), replace: window.location.replace.bind(window.location), setTimeout: window.setTimeout.bind(window), setInterval: window.setInterval.bind(window) }; var _hooksInstalled = false; var _config = null; function init(options) { if (_hooksInstalled) return; _config = normalizeConfig(options); hookWindowOpen(); hookLocationMethods(); interceptLinkClicks(); interceptFormSubmissions(); hookTimeouts(); _hooksInstalled = true; } function disable() { if (!_hooksInstalled)…- 10
- 0

