本页目录
eth_requestAccounts
请求用户提供一个用于识别账户的 Ethereum 地址。如果尚未连接,会弹出连接请求。
参数
无
返回值
string[] — Ethereum 地址数组。需要处理空数组,不要假定账户数量固定。
示例
const accounts = await window.$onekey.ethereum.request({
method: 'eth_requestAccounts'
})
console.log('Connected account:', accounts[0])
// "0x742d35Cc6634C0532925a3b844Bc9e7595f..."连接按钮实现
在连接按钮的点击处理函数中调用 connectWallet(),并在请求结束前禁用按钮,避免重复弹出授权请求。
async function connectWallet() {
const provider = window.$onekey?.ethereum;
if (!provider) throw new Error('OneKey provider not found');
try {
const accounts = await provider.request({ method: 'eth_requestAccounts' });
if (accounts.length === 0) throw new Error('No account was authorized');
return accounts[0];
} catch (error) {
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 4001) {
console.log('Connection request rejected');
} else {
console.error('Connection failed:', error);
}
throw error;
}
}错误
| 错误码 | 消息 | 说明 |
|---|---|---|
| 4001 | User rejected the request | 用户拒绝连接请求 |
| -32002 | Request already pending | 前一个请求仍在等待用户响应 |
说明
- 仅在用户操作(如点击按钮)后调用。
- 用户已连接时,返回已连接账户,不再显示弹窗。
- 对应已弃用的
ethereum.enable()方法。 - 规范见 EIP-1102 。
最后更新于