页面刷新后testUses变量未保存的问题排查与修复建议
问题分析与修复方案
问题描述
运行代码时,预期使用测试密钥登录后累加testUses计数,但实际页面刷新后仍可访问home.html,且testUses始终为0,未按预期更新。询问是否需要将testUses移至函数外部,并寻求修复方案。
核心问题分析
- 条件判断逻辑顺序错误:第一个
if条件inputHash == adminHash || inputHash == testHash已经覆盖了测试密钥的情况,导致后续针对测试密钥的次数限制判断(else if分支)永远不会执行,自然不会更新testUses。 testUses的作用域不是问题:当前在access函数内读取localStorage的写法是合理的,不需要移到函数外部,问题出在逻辑分支的执行顺序上。
修复方案
调整条件判断顺序,先检查测试密钥的次数限制,再处理管理员密钥或无限制的情况,同时确保次数更新逻辑正确执行:
<!DOCTYPE html> <html> <head> <script>window.history.replaceState(null, document.title, "/");</script> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/> <meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="0"/> <title>A-ENGINE</title> <meta name="viewport" content="width=device-width"> <link href='https://fonts.googleapis.com/css?family=Quicksand' rel='stylesheet'> <style> .full { width: 100%; height: 100%; top: 0px; left: 0px; position: absolute; overflow: hidden; } .center { left: 50%; top:50%; transform: translate(-50%, -50%); position: absolute; } </style> </head> <body style='overflow:hidden;padding:0px;visibility:hidden'> <div class='full'> <div class='center' style='width:300px;padding:2px'> <div class="cursor"><div class="planet"></div></div> <input type= password id="access" placeholder="Access Key" onchange="access()"><br> <script> function access() { let input = document.getElementById("access").value; let testUses = +localStorage.getItem('testUses') || 0; const testHash = "cyrb53('a') -> 4625896200565286"; const adminHash = "cyrb53('a') -> 4413594719508086"; const cyrb53 = (str, seed = 0) => { let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed; for (let i = 0, ch; i < str.length; i++) { ch = str.charCodeAt(i); h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); } h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909); h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909); return 4294967296 * (2097151 & h2) + (h1 >>> 0); }; let inputHash = (`cyrb53('a') -> ${cyrb53(input)}`); function home() { document.write('<iframe src="home.html" height="100%" width="100%"></iframe>'); } // 先处理测试密钥的次数限制逻辑 if (inputHash == testHash) { if (testUses <= 1) { home(); testUses++; localStorage.setItem('testUses', testUses); } else { document.getElementById('access').value = ''; } } else if (inputHash == adminHash) { // 管理员密钥无次数限制 home(); } else { document.getElementById('access').value = ''; } } </script> </div> </body> </html>
优化建议
- 避免使用
document.write:该方法在页面加载完成后调用会覆盖整个文档,建议通过DOM操作(如创建iframe元素并添加到页面)来替代。 - 缓存哈希函数结果:如果密钥固定,可以提前计算哈希值并存储,避免每次输入都重新计算。
- 增加会话验证:当前页面刷新后直接显示home.html的问题,是因为
document.write写入iframe后没有后续验证逻辑,建议在home.html中也添加权限校验,或者通过会话存储(sessionStorage)记录登录状态。 - 移除硬编码哈希值:直接在代码中硬编码哈希值存在安全风险,建议通过后端接口验证密钥合法性,避免前端暴露验证逻辑。
内容的提问来源于stack exchange,提问作者StarrySkies
相关产品推荐
相关产品推荐

