简体   繁体   中英

How do I access the user object in a different js file

I made a Google Sign-In login js file that works on the login screen for my website. However, I want to access that user object (that is logged in) on a different page on my website that uses a very different javascript file. How can I get the user object that is logged in on the other javascript file? Also, my knowledge on how asynchronous stuff works is very poor, but if someone could please help me out with this problem I would really appreciate it.

ALSO, on the code snippet, I have shown below I get a really weird bug. When I console.log(name) it outputs an empty string and at one point it was outputting the actual name of the user logged in. However, nowhere on any js file I have I never even initialize the name variable, so I have 0 idea how it is able to grab that data. I then proceeded to close out XAMPP and restart and now it prints out an empty string which is confusing since it should be undefined?

I have already tried reading multiple forums and at this point, I have gotten to the point where I use the firebase.auth().onAuthStateChanged(function(user){...CODE...}); However, the biggest problem is that if I reassign variable names inside of that function to use inside the javascript file it doesn't work since it is an asynchronous function. I basically want to extract information such as the (name = user.displayName, email = user.email, id = user.uid) to use later on in my javascript.

javascript

 firebase.initializeApp(config);
    firebase.auth().onAuthStateChanged(function(user){
        if(user){
            var user = firebase.auth().currentUser;
            userName = user.displayName;
        }
        else {
            console.log("Not Signed In");
        }
    });
    console.log(name);
    console.log(userName);




//SHOWS AN EMPTY STRING ON THIS LINE                       other_file.js:39
Uncaught ReferenceError: userName is not defined           other_file.js:40
    at other_file.js:40

Assign the userName to window object like window.userName = userName in the file where you define your user object. It will be available to use globally.

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