-
Notifications
You must be signed in to change notification settings - Fork 22
/
ChainOrAccountsChanged.html
40 lines (37 loc) · 1.7 KB
/
ChainOrAccountsChanged.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/web3@latest/dist/web3.min.js"></script>
</head>
<body>
<h1>Detect change of account, chain and network</h1>
<pre id="log" style="width:100%;height:200px"></pre>
<script type="text/javascript">
function log(logstr) {
document.getElementById("log").innerHTML +=logstr+"\n";
}
async function f() {
web3 = new Web3(Web3.givenProvider); // provider from metamask
await newChain()
await newActs()
ethereum.on('accountsChanged', newActs)
ethereum.on('chainChanged', newChain);
ethereum.on('networkChanged', newChain); // depricated / still used in metamask mobile
ethereum.on('chainIdChanged', newChain); // depricated / temp workaround
ethereum.autoRefreshOnNetworkChange = false; // temp workaround // doesn't work on metamask mobile
var result=await web3.eth.requestAccounts().catch(x=>{log(x.message);console.log(x);});
async function newChain(newchainId) {
var chainId=await web3.eth.getChainId();
var networkId=await web3.eth.net.getId();
log(`We are on chain: ${chainId} and network ${networkId}`);
}
async function newActs() {
var acts=await web3.eth.getAccounts()
log(`We have accounts: ${JSON.stringify(acts)}`);
}
}
window.addEventListener('DOMContentLoaded', f);
</script>
</body>
</html>