Get all Ethereum accounts from Metamask
Asked Answered
S

2

6

I want to get all the accounts that a user has added in Metamask. I tried all web3.js methods to get accounts, but I always get just one account which is always the currently selected one.

According to web3.js documentation, web3.eth.getAccounts() should return all accounts that this node controls. However, I am getting an array with just the currently selected one. Needless to say, I have multiple accounts created in Metamask.

Starspangled answered 24/10, 2018 at 19:48 Comment(0)
F
2

Documentation says: Account List Reflects User Preference

When a user selects an account in MetaMask, that account silently becomes the web3.eth.accounts[0] in your JS context, the only member of the web3.eth.accounts array.

It depends from web3 provider MetaMask uses by default, I guess. Checkout Why does web3.eth.getAccounts() return only 1 account? question to see that some providers returns more than one account, and it depends from configuration.

Fungiform answered 25/10, 2018 at 21:59 Comment(0)
S
0

Once you call MetaMask's getAccounts(), it prompts users to select a list of accounts to connect. The user can select none (reject), one, or many. Only the user can control that, not the developer implementing the request due to security and privacy considerations.

Note, that the API changed and window.web3 is no longer available. You will have to use the window.ethereum object now:

if (typeof window.ethereum !== 'undefined') {
  // connects to MetaMask
  const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
} else {
  // tell the user to install an `ethereum` provider extension
}
Superannuate answered 22/9, 2021 at 7:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.