Firebase+原生JS实现未登录用户跳转如何避免无限循环问题
问题解决方案
问题根源
无限循环是因为你没有判断当前所处页面就直接执行跳转逻辑:
- 未登录用户打开注册/登录页时,代码检测到无登录态又重复跳转到注册页,形成无限重定向
- 现有代码也没有实现「已登录用户在非首页时跳转到首页」的需求逻辑
修复代码
你可以先获取当前页面的文件名,再根据所处页面判断是否需要执行跳转,修改后的代码如下:
firebase.auth().onAuthStateChanged(user => { // 提取当前页面的文件名 const currentPage = window.location.pathname.split("/").pop(); if (user) { const uid = user.uid; console.log("usuario conectado") // 已登录用户不在首页时才跳转首页 if (currentPage !== 'index.html' && currentPage !== '' && currentPage !== '/') { window.location.href = 'index.html' } } else { // 未登录用户不在注册/登录页时才跳转注册页 if (currentPage !== 'register.html' && currentPage !== 'login.html') { window.location.href = 'register.html' } } })
额外说明
上面代码加了空值和/的判断,是为了兼容域名根路径直接访问首页的场景(比如你的站点首页通过https://yourdomain.com/直接访问,不需要带index.html后缀的情况)。
内容的提问来源于stack exchange,提问作者Caio Menezes
相关产品推荐
相关产品推荐

