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

为什么需要监听网络变化?目前在 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.autoRefreshOnNetworkChange = false 

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

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