为什么URL参数不显示在地址栏或href中?JavaScript重定向参数丢失问题
核心问题排查
1. URL参数消失、获取为null的原因
你的重定向逻辑是页面加载时立即执行的,且判断当前地址时用了完整href全等于根路径/不可用页面路径的逻辑:if (window.location.href == "https://stacker.owenrtcs1051.repl.co/" || ...)
当你手动在地址栏输入带user参数的地址时,完整href已经携带了查询参数,完全匹配不上上面的判断条件,会直接进入else分支跳转到不带参数的页面,自然参数会消失,也拿不到对应值。
2. passkey偶发1分钟空值的原因
你计算passkey的逻辑是基于当前时间的日、时、分相加后乘以32,当系统时间发生分钟级跳变(比如分钟刚好从59跳到00,或者跨小时、跨天的那一瞬间),前后两次计算的passkey会不一致。如果用户刚好在这个时间点提交PIN或者访问页面,就会出现刚生成的passkey和之前的不匹配,看起来就像出现了1分钟的空值窗口期。
具体优化方案
- 地址判断改为仅匹配路径名,忽略查询参数,避免带参数的合法地址被误拦截
- 把passkey的计算逻辑封装成公共函数,避免两处重复代码出现不一致的情况
- 增加参数存在性判断,避免无意义的重定向循环
- 跳转时使用绝对路径或者基于origin的路径,避免相对路径跳转出错
优化后代码示例
公共逻辑(可单独抽成js文件全局引用)
// 封装passkey计算逻辑,全局统一调用 function getCurrentPasskey() { const today = new Date(); const day = today.getDate(); const mins = today.getMinutes(); const hour = today.getHours(); const timestamp = day + hour + mins; return timestamp * 32; } // 封装路径匹配逻辑,忽略查询参数 function matchPath(targetPath) { return window.location.pathname === targetPath; }
重定向逻辑代码
const passkey = getCurrentPasskey(); const url = new URL(window.location.href); const user = url.searchParams.get("user"); const currentHour = new Date().getHours(); console.log(passkey); // 合法参数校验通过 if (user == passkey) { // 仅在根路径或不可用页面时跳转到home页,避免循环跳转 if (matchPath("/") || matchPath("/not-available/")) { console.log(window.location.href); window.location.replace(`/home?user=${passkey}`); } } else { // 校验不通过的分支逻辑 if (currentHour > 19 && currentHour < 20) { if (screen.width < 600) { if (!matchPath("/not-available")) { window.location.replace("/not-available"); } } else { if (matchPath("/") || matchPath("/not-available/")) { console.log(window.location.href); window.location.replace(`/home?user=${passkey}`); } } } else { if (!matchPath("/not-available")) { window.location.replace("/not-available"); } } }
首页devkey函数代码
function devkey() { const passkey = getCurrentPasskey(); console.log(passkey); const pin = prompt("Please insert your dev key.", ""); if (pin == "32") { window.location.replace(`/home?user=${passkey}`); } }
内容的提问来源于stack exchange,提问作者rabitailleow
相关产品推荐
相关产品推荐

