跨HTML页面共享Data_数组及api.html登录权限控制问题
问题描述
- 跨页面数组为空:在LOGIN.html中登录成功后将数据存入
Data_数组,但跳转到api.html后访问该数组始终为空,切换var/let/const声明方式无效。 - 页面访问控制:希望api.html仅允许已登录用户访问,未登录用户无法直接进入。
相关代码
LOGIN.html
<body> <div> <input type="email" id="email" name="email"> <br> <br> <input type="password" id="passsword" name="password" placeholder="password"> <br> <br> <button id="login_btn" onclick="loginForm()">Submit</button> </div> <script src="login.js"></script> </body>
API.html
<body> <h1 id="head">hi</h1> <button onclick="call()">click</button> <script src="login.js"></script> </body>
login.js
const firebaseConfig = { apiKey: "AIpozaSyA_TGCvEOURUERSPpkZbYJLYmbeWEDWFEFWFmlmiAyda", authDomain: "csc130-signup.firebaseapp.com", databaseURL: "https://csc130-signup-default-rtdb.firebaseio.com", projectId: "csc130-signup", storageBucket: "csc130-signup.appspot.com", messagingSenderId: "4425656562363111437507636325742528615729702", appId: "1:424427234625230:web:fccacbccacbcaabfeagd9635909417ffca220531903f3" }; // 初始化firebase firebase.initializeApp(firebaseConfig); // 数据库引用 var signupFormDB = firebase.database().ref('signupForm'); var Data_ = [] function loginForm() { var email = getElementVal('email'); var password = getElementVal('passsword'); firebase.auth().signInWithEmailAndPassword(email, password) .then((userCredential) => { console.log(userCredential); console.log("logged") // 监听用户状态 firebase.auth().onAuthStateChanged(user => { if(user) { signupFormDB.on('value', snapshot => { snapshot.forEach(child => { if(child.val().email == email){ const coin_one = child.val().coin_one; const coin_two = child.val().coin_two; const coin_three = child.val().coin_three; const name = child.val().name; Data_.push(coin_one); Data_.push(coin_two); Data_.push(coin_three); console.log(Data_); window.location = 'api.html'; } }); }); } }); }) .catch((error) => { alert(error); }); } const getElementVal = (id) => { if (document.getElementById(id) == null){ return 0;} else {return document.getElementById(id).value;} }; function call(){ console.log(DATA_); // 注意:此处变量名大小写不匹配,原变量为Data_ }
解决方案
一、解决跨页面Data_数组为空的问题
问题根源
每个浏览器页面拥有独立的JavaScript执行环境,LOGIN.html中的Data_变量和api.html中的Data_是完全独立的两个变量,即便引入同一个JS文件,页面跳转后变量会重新初始化,之前存储的数据无法跨页面传递。此外原代码中call函数里的DATA_大小写错误,也是导致打印为空的原因之一。
推荐解决方法(基于Firebase身份验证,安全可靠)
不需要依赖页面间传值,直接在api.html中通过当前登录用户的身份从数据库读取对应数据:
修改login.js,添加页面初始化逻辑:
// 在login.js末尾添加以下代码 // 页面加载时检查用户状态并获取数据 firebase.auth().onAuthStateChanged(user => { if (user) { // 已登录,根据用户邮箱查询数据库(邮箱唯一) signupFormDB.orderByChild('email').equalTo(user.email).once('value', snapshot => { const userEntries = snapshot.val(); if (userEntries) { // 取第一个匹配的用户数据 const userData = Object.values(userEntries)[0]; // 重新赋值全局Data_数组 Data_ = [userData.coin_one, userData.coin_two, userData.coin_three]; console.log('当前用户硬币数据:', Data_); } }); } }); // 修正call函数的变量名大小写问题 function call(){ console.log(Data_); }
备选方法(本地存储,适合简单场景)
登录成功后将数据存入sessionStorage,api.html中读取:
- 在LOGIN.html的登录成功回调中添加:
sessionStorage.setItem('userCoins', JSON.stringify(Data_)); - 在api.html的
call函数中读取:function call(){ const savedData = sessionStorage.getItem('userCoins'); Data_ = savedData ? JSON.parse(savedData) : []; console.log(Data_); }
注意:本地存储数据可被用户手动修改,敏感数据不建议用此方法。
二、实现api.html仅登录后可访问
利用Firebase Auth的onAuthStateChanged监听用户状态,若未登录则自动跳转到登录页:
在login.js中添加以下代码(放在firebase初始化之后):
// 页面访问控制:仅允许已登录用户访问api.html if (window.location.pathname.includes('api.html')) { firebase.auth().onAuthStateChanged(user => { if (!user) { // 未登录,跳转到登录页 window.location.href = 'LOGIN.html'; } }); }
这样用户直接访问api.html时,如果未登录会被自动重定向到LOGIN.html,只有登录成功后才能进入api.html。
内容的提问来源于stack exchange,提问作者Brown Canadian
相关产品推荐
相关产品推荐

