You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过新版MetaMask的ethereum API获取账户列表?

新版MetaMask通过ethereum API获取账户列表的方法

首先确认你的页面运行环境已安装MetaMask插件,此时浏览器会注入全局window.ethereum对象,所有钱包交互都通过该对象完成。

方法1:首次连接请求授权并获取账户

调用eth_requestAccounts方法会触发MetaMask的授权弹窗,用户同意连接后会返回账户数组:

// 先检测MetaMask是否安装
if (typeof window.ethereum !== 'undefined') {
  try {
    // 请求用户授权连接钱包,返回的数组即为授权的账户列表
    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
    // 列表第一个元素为当前用户在MetaMask选中的活跃账户
    const currentActiveAccount = accounts[0];
    console.log('账户列表:', accounts);
  } catch (error) {
    // 用户拒绝授权等异常处理
    if (error.code === 4001) {
      console.log('用户拒绝了钱包连接请求');
    } else {
      console.error('获取账户失败:', error);
    }
  }
} else {
  console.log('请安装MetaMask插件');
}

方法2:已授权场景下静默获取账户

如果用户之前已经同意过站点的钱包连接请求,可以直接调用eth_accounts方法获取账户,不会触发弹窗:

if (typeof window.ethereum !== 'undefined') {
  const accounts = await window.ethereum.request({ method: 'eth_accounts' });
  // 未授权的话返回空数组,已授权返回对应的账户列表
  if (accounts.length > 0) {
    console.log('已授权账户列表:', accounts);
  } else {
    console.log('当前站点未获得钱包授权,请先调用eth_requestAccounts申请授权');
  }
}

注:原来的window.web3是MetaMask早期注入的Web3实例,目前已经废弃,所有操作统一通过window.ethereum的request方法调用JSON-RPC接口实现。
你遇到的Uncaught TypeError: web3.eth is undefined报错就是因为window.web3已经不存在,迁移到上述ethereum API调用方式即可解决。

内容的提问来源于stack exchange,提问作者l5y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:39:05