【发布时间】:2020-03-31 13:40:50
【问题描述】:
我查看了这里的文档https://metamask.github.io/metamask-docs/Main_Concepts/Getting_Started
但我不确定如何检测退出 MetaMask 的用户?
【问题讨论】:
我查看了这里的文档https://metamask.github.io/metamask-docs/Main_Concepts/Getting_Started
但我不确定如何检测退出 MetaMask 的用户?
【问题讨论】:
Metamask 文档建议您在更改帐户时刷新页面。
const setAccountListener = (provider) => {
provider.on("accountsChanged", (_) => window.location.reload());
provider.on("chainChanged", (_) => window.location.reload());
};
然后打电话给useEffect
useEffect(() => {
// Load provider
if (provider) {
....
setAccountListener(provider);
// add more logic
} else {
console.error("Please, install Metamask.");
}
};
}, []);
【讨论】:
来自 MetaMask Ethereum Provider API:
ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);
只要 eth_accounts RPC 方法的返回值发生更改,MetaMask 提供程序就会发出此事件。 eth_accounts 返回一个空数组或包含单个帐户地址。返回的地址(如果有)是允许调用者访问的最近使用的帐户的地址。调用者由其 URL 来源标识,这意味着具有相同来源的所有站点共享相同的权限。
【讨论】:
window.ethereum.on('accountsChanged', (accounts) => {
// If user has locked/logout from MetaMask, this resets the accounts array to empty
if (!accounts.length) {
// logic to handle what happens once MetaMask is locked
}
});
因此,使用上述您可以检测 MetaMask 的锁定/注销。
【讨论】:
window.ethereum.on('accountsChanged', function (accounts) {
let acc = accounts[0]
如果他们退出,acc 将是未定义的。
【讨论】: