DApp Development – How to Auto Reload DApp When MetaMask is Unlocked or Locked by User

dapp-designdapp-developmentmetamask

How can I auto-reload dapp base on Metamask account status?

I wish to design a metamask based authentication (like the one used in Crypokitties), for which I am able to design code which identifies if Metamask is locked or not. But the challenge is I have to manually refresh my web page to capture the latest status of metamask if it is locked or unlocked.

Suppose, if a user logs out of metamask, I want to catch that instance and close the dapp at the same time without any further action from the user (in my case this happens only after I manually refresh the page).

Will be grateful if someone has created similar feature and can guide with logic or code snippets.

Best Answer

As Metamask injects a Web3 instance in window object you can check for existence of the object. In order to detect if metamask is unlocked you can check in the Web3 instance if there's some address available.

To refresh the data automatically in JavaScript you can then use setInterval(MyCheckingMethod,1000); in your main application instance.

A quick example below, but you'll find that most is taken from the official page . Note that this is just a mostly empty but commented example you'll have to adapt for your own use-case & data flow :

export detectWeb3 = () => {
    if(typeof window.web3 !== "undefined" ){ // load metamask's provider
        const w3 = window.web3;

        // Calling method to retrieve accounts. Method available since Web3 v1.x.x-beta
        w3.eth.getAccounts().then( r => {
            if (r.length > 0) { 
                // some addresses found.
            } else {
                // No address found
            }
        }).catch(e => { // Error catched if method doesn't exist
            const accounts = w3.eth.accounts; // We'll try to get accounts from previous versions ( up to Web3 v0.20.x)
            if (accounts.length > 0) {
                // some addresses found 
            } else {
                // No address found
            }
        });
    }else{ 

        // Instructions to execute if no Web3 instance has been detected.  

    }
}

setInterval(detectWeb3,1000);

Another disclaimer : i took part of the code from a bunch of typescript files of mine. You might need to take this in consideration.

Related Topic