如何在Firebase Auth UI验证后获取并存储用户手机号至Cookie
Hey there! Let's break down exactly how to grab the user's phone number after Firebase Auth UI's phone verification and store it in a cookie for your Google Maps marker labels.
Where to put the code to get the phone number
The key is to hook into Firebase Auth UI's success callback or the global auth state listener—these are the most reliable places to access the verified user's details right after verification completes.
Option 1: Use the Auth UI signInSuccessWithAuthResult callback
This is the most direct approach because it triggers immediately when the user finishes verifying their phone number through Auth UI. Here's how to implement it in your existing Auth UI setup:
// Initialize Firebase Auth UI const ui = new firebaseui.auth.AuthUI(firebase.auth()); const uiConfig = { signInOptions: [ firebase.auth.PhoneAuthProvider.PROVIDER_ID // Your phone verification option ], // This callback runs right after successful sign-in/verification signInSuccessWithAuthResult: function(authResult, redirectUrl) { // Get the verified user object directly from the auth result const verifiedUser = authResult.user; const userPhoneNumber = verifiedUser.phoneNumber; // Store the phone number in a cookie (example: expires in 7 days) if (userPhoneNumber) { const expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toUTCString(); document.cookie = `userPhone=${userPhoneNumber}; expires=${expiryDate}; path=/`; } // Return false if you don't want Firebase to auto-redirect the user return false; } }; // Start the Auth UI in your container element ui.start('#firebaseui-auth-container', uiConfig);
Why this works: Using authResult.user is more reliable than calling firebase.auth().currentUser directly here, because it's the exact user object returned from the verification flow—no risk of async timing issues.
Option 2: Listen to global auth state changes
If you want to handle cases where the user might already be signed in (like after a page refresh), use this global listener. It will trigger whenever the user's auth state changes (sign-in, sign-out, verification):
firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in/verified—grab their phone number const userPhoneNumber = user.phoneNumber; if (userPhoneNumber) { const expiryDate = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toUTCString(); document.cookie = `userPhone=${userPhoneNumber}; expires=${expiryDate}; path=/`; } } else { // User signed out—clear the cookie if needed document.cookie = "userPhone=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; } });
Using the cookie in Google Maps
Once the cookie is set, you can retrieve it and use it for your marker labels with a simple helper function:
// Helper function to get a cookie by name function getCookie(cookieName) { const cookieValue = `; ${document.cookie}`; const cookieParts = cookieValue.split(`; ${cookieName}=`); if (cookieParts.length === 2) return cookieParts.pop().split(';').shift(); } // Get the phone number from the cookie const userPhone = getCookie('userPhone'); // Use it in your Google Maps marker const marker = new google.maps.Marker({ position: yourLatLngCoordinates, // Replace with your marker's lat/lng map: yourMapInstance, // Replace with your map object label: userPhone });
Quick check to confirm
After verification, open your browser's DevTools → Application tab → Cookies section. You should see a userPhone cookie with the verified phone number stored there.
内容的提问来源于stack exchange,提问作者user3741622

