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 :
Another disclaimer : i took part of the code from a bunch of typescript files of mine. You might need to take this in consideration.