Web3js
如何檢測 Metamask 上的使用者帳戶是否在前端斷開連接
我正在嘗試建構一個 web3 應用程序。在我的前端,我想檢測使用者是否在 Metamask 錢包上更改了他的帳戶或斷開連接,並希望在前端顯示此更改。我該怎麼做?
const [account, setaccount] = useState('0x0'); window.ethereum.on('accountsChanged',async (accounts) =>{ const changedAccounts =await window.ethereum.request({method: 'eth_requestAccounts'}); setaccount(changedAccounts[0]); console.log('changedAccounts') }) useEffect(async () => { if(!window.ethereum){ window.alert('Please consider installing Metamask'); }else{ const accounts =await window.ethereum.request({method: 'eth_requestAccounts'}); setaccount(accounts[0]); } if(!window.ethereum.isConnected()){ console.log('Disconnected') }else{ console.log('Connected') } console.log('useEffect') }, [account]);
有更多事件需要監聽,涵蓋所有案例。此外,應該將事件訂閱和清理移到 a
useEffect
中,以防止記憶體洩漏。這是一個可以幫助您入門的範例…
const [account, setaccount] = useState('0x0'); useEffect(() => { if (!window.ethereum) { // Nothing to do here... no ethereum provider found return; } const accountWasChanged = (accounts) => { setaccount(accounts[0]); console.log('accountWasChanged'); } const getAndSetAccount = async () => { const changedAccounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); setaccount(changedAccounts[0]); console.log('getAndSetAccount'); } const clearAccount = () => { setaccount('0x0'); console.log('clearAccount'); }; window.ethereum.on('accountsChanged', accountWasChanged); window.ethereum.on('connect', getAndSetAccount); window.ethereum.on('disconnect', clearAccount); window.ethereum.request({ method: 'eth_requestAccounts' }).then(accounts => { console.log('accounts', accounts); // No need to set account here, it will be set by the event listener }, error => { // Handle any UI for errors here, e.g. network error, rejected request, etc. // Set state as needed }) return () => { // Return function of a non-async useEffect will clean up on component leaving screen, or from re-reneder to due dependency change window.ethereum.off('accountsChanged', accountWasChanged); window.ethereum.off('connect', getAndSetAccount); window.ethereum.off('disconnect', clearAccount); } }, [/* empty array to avoid re-request on every render, but if you have state related to a connect button, put here */]);