【问题标题】:Detect MetaMask logout (Ethereum)检测 MetaMask 注销(以太坊)
【发布时间】:2020-03-31 13:40:50
【问题描述】:

我查看了这里的文档https://metamask.github.io/metamask-docs/Main_Concepts/Getting_Started

但我不确定如何检测退出 MetaMask 的用户?

【问题讨论】:

    标签: ethereum metamask


    【解决方案1】:

    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.");
          }
        };
    
       
      }, []);
    

    【讨论】:

      【解决方案2】:

      来自 MetaMask Ethereum Provider API:

      ethereum.on('accountsChanged', handler: (accounts: Array<string>) => void);
      

      只要 eth_accounts RPC 方法的返回值发生更改,MetaMask 提供程序就会发出此事件。 eth_accounts 返回一个空数组或包含单个帐户地址。返回的地址(如果有)是允许调用者访问的最近使用的帐户的地址。调用者由其 URL 来源标识,这意味着具有相同来源的所有站点共享相同的权限。

      【讨论】:

        【解决方案3】:
        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 的锁定/注销。

        【讨论】:

          【解决方案4】:
              window.ethereum.on('accountsChanged', function (accounts) {
                let acc = accounts[0]
          

          如果他们退出,acc 将是未定义的。

          【讨论】:

            猜你喜欢
            • 2022-01-19
            • 2022-09-17
            • 1970-01-01
            • 2021-03-24
            • 2019-03-29
            • 2020-01-27
            • 2021-11-15
            • 2021-07-20
            • 2022-08-16
            相关资源
            最近更新 更多