通过JavaScript实现禁止js跳转到非本站域名外的其它域名代码示例

以下是一段实现禁止跳转到非本站域名的JavaScript代码:

// 设置允许的域名白名单(包括主域名及其子域名)
const allowedDomains = [
    location.hostname, // 当前域名
    'trusted-site.com', // 其他可信域名
    'subdomain.my-site.com' // 子域名
];

// 监听所有链接点击事件
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
});

功能说明:

  1. 链接点击拦截

    • 自动检测所有<a>标签点击

    • 解析目标URL的域名

    • 检查是否在允许域名白名单内

    • 阻止非白名单域名的跳转

  2. 域名白名单

    • 自动包含当前站点域名

    • 支持添加多个可信域名

    • 支持子域名匹配(如 .example.com 匹配所有子域)

  3. 特殊跳转防护

    • 拦截通过 window.location = ... 的跳转

    • 处理各种类型的链接(相对路径/绝对路径)

    • 忽略JavaScript伪协议链接

使用说明:

  1. 将上述代码放入<script>标签或JS文件中

  2. 修改allowedDomains数组添加你的可信域名

  3. 阻止跳转时会显示警告信息(可根据需求修改提示方式)

  4. 支持现代浏览器(IE需补充URL polyfill)

注意事项:

  • 对于动态创建的链接同样有效(事件委托)

  • 不会阻止浏览器默认行为(如新标签页打开)

  • 需要HTTPS环境下才能完全阻止部分现代浏览器的跳转

  • 无法100%防止所有跳转方式(如meta refresh、HTTP重定向)

提示:若要处理页面重定向,需要在服务器端配合设置(如CSP的navigate-to指令)

本文来自投稿,不代表首晒立场,如若转载,请注明出处:https://www.shoushai.com/p/1581

喜欢 (0)

发表回复

登录后才能评论

猜你喜欢