我正在尝试这样做,以便当用户点击我的登录表单上的提交按钮时,他们将以Firebase中的匿名用户身份登录。我知道我的提交按钮正在触发jQuery提交事件,因为正在显示其中的警报。但是,即使提交按钮触发jQuery提交事件,也不会因某种原因调用signInAnonymously
方法。我也尝试过将signInAnonymously
调用放在一个单独的函数中并使用onsubmit
形式的属性,但这也不起作用。这是我的代码(出于安全目的,我省略了我的配置详细信息):
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags always come first -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Escape Room</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="styles.css">
<!-- jQuery -->
<script src="resources/jquery/jquery-3.1.1.slim.min.js"></script>
<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.6.2/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: "",
messagingSenderId: ""
};
firebase.initializeApp(config);
//Initialize authentication
var auth = firebase.auth();
// Handle authenticated users
auth.onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
// ...
} else {
// User is signed out.
// ...
}
// ...
});
// When the DOM has loaded
$(document).ready(function(e) {
$('#signIn').submit(function(e) {
// Prevent the page from refreshing
e.preventDefault();
alert("test");
// Authenticate user
auth.signInAnonymously().catch(function(error) {
alert('test2');
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.error(error);
});
});
});
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-12">
<form id="signIn">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" placeholder="Your Name">
</div>
<div class="form-group">
<label for="vest">Vest Number</label>
<input type="text" class="form-control" placeholder="Vest Number">
</div>
<button type="submit" class="btn btn-primary">Start</button>
</form>
</div>
</div>
</div>
<!-- jQuery first, then Tether, then Bootstrap JS. -->
<script src="resources/jquery/jquery-3.1.1.slim.min.js"></script>
<script src="resources/tether/js/tether.min.js"></script>
<script src="resources/bootstrap/js/bootstrap.min.js"></script>
</body>
</html>
我对Firebase比较陌生,这让我感到困惑,所以任何帮助都会非常感激!
答案 0 :(得分:1)
我发现了什么问题。由于我从未调用firebase.auth().signOut()
,因此我保持以同一用户身份登录,因此每次提交表单时都没有创建新用户,因为我已经以用户身份登录。我在脑海中添加了window.onload = auth.signOut();
脚本,现在每次按下提交按钮都会创建一个新用户。