How to open metamask to get the address?

Hi, I’m trying to create a web app using React that user first need to login using email, then they can connect multiple metamask addresses to the web app.

I can signup using email, but I do not know how to connect metamask without logging in. If I use the login with metamask from Moralis, it will create a new user which is not what I want.

I have read through this forum link which has similar attempt, but it stopped there saying use web3.eth.getAccounts()

I learned that it doesn’t require web3 for us to open Metamask. Technically we can do it using window.ethereum.request, but from my code here the metamask window is still not opening.

This is my code

import React from "react";

export const Metamask = () => {
  const signMetamask = () => {
    if (window.ethereum) {
      window.ethereum.request({ method: "eth_requestAccounts" });
      console.log("MetaMask is installed!");
    }
  };

  return <button onClick={() => signMetamask()}>Open Metamask</button>;
};

If I click the button, I got the console.log result MetaMask is installed! but the metamask window is not opened.

Please help to make it work. Thank you

usually you have to use enableWeb3 in order to have access to MetaMask

Thanks for your reply.

Turns out I am already connected. So I need to disconnect first (user can only do it manually), then clicking the same button will open the metamask window to connect.

Since I am already connected I can get the address by

const ethacc = await window.ethereum.request({ method: "eth_accounts" });
console.log("etacc: ", ethacc);

Another different thing that I just realized was Metamask Signature Request. This is the one that we use when logging in to Moralis. But it’s actually different purpose from connecting to metamask wallet. I might need it later too.