使用Gmail OAuth限制仅指定邮箱登录时出现页面反复刷新问题
问题原因
无限重载的核心原因是你允许访问后跳转的目标页./index.html也加载了Google OAuth的初始化逻辑,用户完成登录后OAuth会自动触发onSignIn回调,回调里又再次执行跳转到./index.html的逻辑,最终形成无限循环。
修复方案
- 新增登录状态标识:登录校验通过后,在
sessionStorage里写入已登录的标记,回调触发时先判断是否已有登录标记,避免重复跳转;如果需要长期记住登录状态可以替换为localStorage,登出时同步清除即可 - 拆分页面逻辑:登录页仅处理登录校验逻辑,内部页(比如index.html)不需要执行登录跳转逻辑,反而要补充未登录状态拦截,检测到未登录时跳回登录页
- 补充空值校验:获取到邮箱后先判断是否为空,避免scope权限不足时的逻辑异常
- 无权限场景补充登出逻辑:校验不通过时主动登出当前Google账号,避免下次打开页面直接触发无权限提示
修改后的代码示例
登录页onSignIn逻辑
function onSignIn(googleUser) { // 已登录状态下直接终止逻辑,避免重复跳转 if (sessionStorage.getItem('isLogin') === 'true') { return } var profile = googleUser.getBasicProfile(); console.log('Name: ' + profile.getName()); const userEmail = profile.getEmail() console.log('Email: ' + userEmail); // 补充邮箱空值校验 if (!userEmail) { alert("无法获取邮箱信息,请检查授权权限") return } // 允许登录的邮箱校验 if (userEmail == "XXXXXXXX@gmail.com") { // 写入登录状态 sessionStorage.setItem('isLogin', 'true') window.location.href = "./index.html" } else { let done = confirm("You don't have permission to access this.") // 先登出当前无权限的Google账号 const auth2 = gapi.auth2.getAuthInstance(); if (done) { auth2.signOut().then(function () { window.location.href = "https://www.HOMEPAGEco.uk/" }); } else { auth2.signOut().then(function () { alert("Please try again.") }); } } }
内部页(index.html)补充校验逻辑
// 页面加载时判断登录状态,未登录跳回登录页 window.onload = function() { if (sessionStorage.getItem('isLogin') !== 'true') { window.location.href = "./login.html" // 替换为实际登录页地址 } } // 可选:补充登出功能 function logout() { const auth2 = gapi.auth2.getAuthInstance(); auth2.signOut().then(function () { sessionStorage.removeItem('isLogin') window.location.href = "./login.html" }); }
内容的提问来源于stack exchange,提问作者Murchie
相关产品推荐
相关产品推荐

