為什么需要監聽網絡變化?目前在 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