如何为Cookie检测函数新增条件且避免触发无限循环
问题根源
- 新增的第三个判断分支存在自定向错误:当当前路径已经是
/Important_Safety_Information.html时,你依然执行window.location.replace('/Important_Safety_Information.html'),页面每次加载都会触发重定向,形成无限循环。 - 逻辑优先级错误:你把安全信息页的判断放在了非法语站定向到
/landing.html的分支之后,非法语站下只要当前路径不是/landing.html,会直接被第二个分支拦截定向,第三个分支永远不会触发。
修复方案
你可以先定义无需重定向的页面白名单,再执行对应逻辑,避免重复判断和自定向问题。如果你的需求是允许未登录用户直接访问安全信息页,调整后的代码如下:
function checkCookie() { var current_url = window.location.pathname; var logInCookie = _siteNS.Utils.readCookie('x-access'); // 无需重定向的页面白名单 const allowedPages = ['/landing-fr.html', '/landing.html', '/Important_Safety_Information.html']; if (!logInCookie) { // 当前页在白名单内直接跳过重定向 if (allowedPages.includes(current_url)) return; // 按语言定向到对应落地页 window.location.replace( window.location.toString().includes('-fr') ? '/landing-fr.html' : '/landing.html' ); } }
如果你的需求是未登录的非法语用户需要优先跳转到安全信息页,而非通用落地页,调整代码如下:
function checkCookie() { var current_url = window.location.pathname; var logInCookie = _siteNS.Utils.readCookie('x-access'); const isFrSite = window.location.toString().includes('-fr'); if (!logInCookie) { // 优先处理非法语站安全信息页定向逻辑 if (!isFrSite && current_url !== '/Important_Safety_Information.html') { window.location.replace('/Important_Safety_Information.html'); return; } // 处理普通落地页定向逻辑 if (isFrSite && current_url !== '/landing-fr.html') { window.location.replace('/landing-fr.html'); } else if (!isFrSite && current_url !== '/landing.html') { window.location.replace('/landing.html'); } } }
内容的提问来源于stack exchange,提问作者hendy0817
相关产品推荐
相关产品推荐

