简体   繁体   中英

How to get just the first name when a user logs in using social media with firebase?

Here is the code that I am using to get the details of the user when they log in using google, facebook or twitter.

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var emailVerified = user.emailVerified;
        var photoURL = user.photoURL;
        var uid = user.uid;
        var phoneNumber = user.phoneNumber;
        var providerData = user.providerData;
        user.getToken().then(function(accessToken) {

            console.debug('user', user);

            document.getElementById('name').textContent = displayName;
            document.getElementById("avatar").src = photoURL;


        });

    } else {
        console.log('not logged in');

    }

});

Then in the html by writing <p id="name"></p> the entire name of the user is displayed.

How do I display just the first name of the user?

你可以这样做;

document.getElementById('name').textContent = (displayName.split(' '))[0];

First and last name are available from most social providers just after you log in, but you will need to save them to your database as Firebase does not. What each provider calls first and last name varies, though.

Documentation at https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signinwithpopup

 firebase.auth .signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then((user) => { const firstName = user.additionalUserInfo.profile.given_name; const lastName = user.additionalUserInfo.profile.family_name; }); firebase.auth .signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com')) .then((user) => { const firstName = user.additionalUserInfo.profile.givenName; const lastName = user.additionalUserInfo.profile.surname; });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM