I'm using the next function to get the first account from user's MetaMask:

var account = web3.eth.getAccounts((error,result) => {
        if (error) {
        } else {
            return result[0];

However the user could have selected any other account from his MM not just the first one, or switch the account anytime. How to get the current selected account?

4 Answers 4

async function onInit() {
        await window.ethereum.enable();
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        const account = accounts[0];
         window.ethereum.on('accountsChanged', function (accounts) {
            // Time to reload your interface with accounts[0]!


try this!!


First of all your website must be allowed to connect MetaMask. This can be achieved by adding the website url in MetaMask -> Settings -> Connections. If you want dynamic solution for your users your website need to run this code whenever your it's loaded so your users don't have to deal manual whitelisting your website:

if(window.ethereum) {
    await ethereum.enable();

(latest MetaMask comes with window.ethereum variable)

Now after doing that you can define the following method:

function getAccounts(callback) {
    web3.eth.getAccounts((error,result) => {
        if (error) {
        } else {

And then whenever I need the current account I can call it like this:

getAccounts(function(result) {
  • I'm connecting MM and I'm retrieving all the accounts using web3.eth.getAccounts() as stated in my question. However the first element in the result is not the selected user account, it's just the first account in MM
    – Veilkrand
    Jan 17, 2020 at 6:54
  • Please a look on this video I just recorded. streamable.com/m8xlx Jan 17, 2020 at 7:25
  • I appreciate the effort making the video. Is it possible to handle the account switch event?
    – Veilkrand
    Jan 24, 2020 at 2:10
  • 1
    Sure, you can do it by using this code pastebin.com/cucCmY1v . I also recorded it so you can follow up here streamable.com/3cqy4 . Let me know if you succeed. Jan 24, 2020 at 5:21
  • This the first account right? Not the current account.
    – GN.
    Dec 13, 2020 at 7:15

When a user account changes on Metamask, you can detect and update it on your interface asynchronously without the need to reload your page as follows, for an example:

const checkCurrentAccount = () => {
 if (window.ethereum) {
   window.ethereum.on("accountsChanged", async () => {
    const accounts = await window.ethereum.request({
      method: "eth_accounts",

useEffect(() => {
}, []);

I wonder why its so difficult to understand the question asked. The answer is : window.ethereum.selectedAddress will give you current selected address


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.