[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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM