When sign into metamask, reload page once on page load

Hi, im having troubles with my metamask load. On initial load, my site does not recognise that a user is sign in or not to metamask until the page is manually refreshed. Im trying to have my page reload once when the site is first started up to recognise if a user is logged in or not. If the user is not signed in, they should log in to their metamask using the chrome extension. Once they log in, i want the page to reload so the site can recognise that the user is logged in and proceed with the run.

This is apart of my code:

init = async () => {
    web3 = new Web3(window.ethereum);

    web3.eth.getAccounts(function(err, accounts){
        document.body.style.overflow = 'hidden';
        if (err != null) {console.error("An error occurred: "+err);
    }else if (accounts.length == 0) {console.log("User is not logged in to MetaMask");
}else {window.onload = function() {
            if(!window.location.hash) {
                window.location = window.location + '#loaded';
                window.location.reload();
            }
        }
        initUser();
        console.log("User is logged in to MetaMask");
    }  
    });
    await Moralis.enableWeb3();
    
   
};

Console log (when the page is first loaded):

Screenshot 2022-07-06 104403

Basically, i want the following logs to run without the need to manually refresh the page before hand…

Console log (when site is refreshed but the user is not logged in):

refresh_notlogin

Console log (when site is refreshed and the user is logged in):

refresh_login

basically, im just having trouble in using this method properly:

//reload page once 
window.onload = function() {
            if(!window.location.hash) {
                window.location = window.location + '#loaded';
                window.location.reload();

Remove the window.onload part.

1 Like