Web端JavaScript使用Firestore onAuthStateChanged时浏览器无限循环问题
问题根因
无限循环的核心是这段状态监听没有校验当前所在页面,无论用户状态匹配的目标页是否就是当前打开的页面,都会强制触发跳转。页面跳转后重新加载,会再次触发onAuthStateChanged回调,进入无限跳转/刷新循环,典型的触发场景有两个:
- 用户未登录时打开
index.html,代码命中else分支强制跳转index.html,页面刷新后重复触发逻辑 - 用户已登录时打开
dashboard.html,代码命中if分支强制跳转dashboard.html,页面刷新后重复触发逻辑
修复方案
在跳转前增加当前页面路径的判断,仅当当前页面不是目标页时才执行跳转操作,修改后的代码如下:
auth.onAuthStateChanged(user => { const currentPath = window.location.pathname; if (user) { console.log('user is signed in', user); // 仅当前未在仪表盘页面时跳转 if (!currentPath.includes('dashboard.html')) { window.location.assign('dashboard.html'); } } else { console.log('user is NOT signed in'); // 仅当前未在首页时跳转,兼容根路径默认加载index.html的场景 if (!currentPath.includes('index.html') && currentPath !== '/') { window.location.assign('index.html'); } } })
如果你的站点根路径(/)不会默认加载index.html,可以去掉上面else分支里的&& currentPath !== '/'判断。
可选优化
你也可以把状态监听逻辑拆分到对应页面,避免全局冗余判断:
- 仅在
index.html加入监听:用户已登录时跳转到dashboard.html - 仅在
dashboard.html加入监听:用户未登录时跳转到index.html
内容的提问来源于stack exchange,提问作者Ian Barber
相关产品推荐
相关产品推荐

