[Contract] 监听 MetaMask 网络变化, 账号切换

时间:2020-03-03 20:47:06   收藏:0   阅读:237

 

为什么需要监听网络变化?目前在 MetaMask 中切换网络,网页会自动刷新,但是这一特性后面将停止使用。

MetaMask: MetaMask will soon stop reloading pages on network change.

If you rely upon this behavior, add a ‘networkChanged‘ event handler to trigger the reload manually: https://metamask.github.io/metamask-docs/API_Reference/Ethereum_Provider#ethereum.on(eventname%2C-callback)

Set ‘ethereum.autoRefreshOnNetworkChange‘ to ‘false‘ to silence this warning: https://metamask.github.io/metamask-docs/API_Reference/Ethereum_Provider#ethereum.autorefreshonnetworkchange

 

通过提示得知,我们需要监听事件来得知网络切换,从而处理自定义的逻辑。

ethereum.on(‘networkChanged‘, function (networkIDstring) {
  // ...
})

 

同样,检测账号切换如下

ethereum.on(‘accountsChanged‘, function (accounts) {
  // Time to reload your interface with accounts[0]!
})

 

Ref:https://metamask.io/metamask-docs/guide/ethereum-provider.html#methods-current-api

Link:https://www.cnblogs.com/farwish/p/12393428.html

原文:https://www.cnblogs.com/farwish/p/12393428.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!