You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript检测用户是否从旧域名重定向至新域名并触发模态框?

实现域名重定向后的来源检测与模态框触发

直接说结论:可以实现需求,但不同重定向方式的检测逻辑差异很大——你说的没错,DNS重定向确实做不到;负载均衡/服务器端重定向是最优方案,前端JS重定向也可行,下面分方案详细说明:

一、服务器端(负载均衡)重定向方案(最优)

这种方式最可靠,因为可以在重定向过程中主动传递"来源标识",不受浏览器策略限制。

方案1:重定向时附加查询参数

以Nginx为例,配置olddomain的重定向规则时,给newdomain的URL加一个专属参数:

server {
    server_name olddomain.com;
    # 301永久重定向,同时追加?from_old=1参数
    return 301 $scheme://newdomain.com$request_uri?from_old=1;
}

然后在newdomain的页面JS中检测该参数,触发模态框:

window.addEventListener('DOMContentLoaded', () => {
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.has('from_old')) {
        // 替换成你的模态框逻辑,这里用alert做示例
        alert("hey, we just changed our name to newdomain");
        // 移除URL参数,避免用户刷新页面后重复弹窗
        urlParams.delete('from_old');
        window.history.replaceState({}, document.title, window.location.pathname + (urlParams.toString() ? `?${urlParams.toString()}` : ''));
    }
});

方案2:重定向时设置Cookie

如果不想修改URL,也可以在重定向时给newdomain设置临时Cookie:

server {
    server_name olddomain.com;
    return 301 $scheme://newdomain.com$request_uri;
    # 设置1小时有效期的Cookie,仅在newdomain生效
    add_header Set-Cookie "from_old=1; path=/; domain=newdomain.com; expires=1h";
}

然后在newdomain的页面中读取Cookie并触发弹窗:

// 简易Cookie读取函数
function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}

window.addEventListener('DOMContentLoaded', () => {
    if (getCookie('from_old')) {
        alert("hey, we just changed our name to newdomain");
        // 弹窗后删除Cookie,避免重复触发
        document.cookie = "from_old=; path=/; domain=newdomain.com; expires=Thu, 01 Jan 1970 00:00:00 GMT";
    }
});

二、前端JS重定向方案

如果只能在前端实现跳转(比如无法修改服务器配置),可以在olddomain的页面中通过JS跳转时附加参数:

// olddomain页面的JS代码
if (window.location.hostname === 'olddomain.com') {
    // 跳转时携带来源标识参数
    window.location.href = `https://newdomain.com${window.location.pathname}?from_old=1`;
}

newdomain的页面JS逻辑和服务器端方案1完全一致,检测from_old参数即可。

⚠️ 缺点:如果用户禁用JavaScript,重定向会失效,所以仅适合无法操作服务器的场景。

三、为什么DNS重定向不行?

DNS重定向是在域名解析层面完成的,浏览器只会收到最终的IP地址,完全不知道最初请求的是olddomain,因此没有任何方式能检测到"来自olddomain"这个行为,确实无法实现需求。

四、关于Referer的注意事项

不要依赖document.referrer检测来源——很多浏览器默认会在跨域重定向时隐藏Referer,用户也可以手动禁用Referer发送,这个方法的可靠性极低,不能作为唯一检测手段。

内容的提问来源于stack exchange,提问作者zuroslav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:01:27