skip to Main Content

I am trying to have the MetaMask wallet to stay connected upon the page refresh. However, I could not find any info on that matter on the world-wide-web. Sad. Also, from what I’ve managed to find, there was supposedly a MM privacy update in 2019, which cut out the injection method…so, is there a way to do it natively with pure JS?

The code so far:

const getWeb3 = async () => {
    return new Promise(async (resolve, reject) => {
        const web3 = new Web3(window.ethereum)
        
        try {
            await window.ethereum.request({ method: "eth_requestAccounts" })
            resolve(web3)
        } catch (error) {
            reject(error)
        }
    })
}

document.addEventListener("DOMContentLoaded", () => {
    document.getElementById("connect_button").addEventListener("click", async ({ target }) => {
        const web3 = await getWeb3()
        const walletAddress = await web3.eth.requestAccounts()
        const walletShort = walletAddress.toString()
        const walletBalanceInWei = await web3.eth.getBalance(walletAddress[0])
        const walletBalanceInEth = Math.round(Web3.utils.fromWei(walletBalanceInWei) * 100) / 100
        
        target.setAttribute("hidden", "hidden")
        
        document.getElementById("wallet_balance").innerText = walletBalanceInEth
        document.getElementById("wallet_info").removeAttribute("hidden") 
        document.getElementById("address_shrt").innerText = walletShort.slice(0,3) + '...' + walletShort.slice(-3)
       
    })
})

I have no idea about react whatsoever, so react guides are kinda gibberish to me. Any useful links or directions I could follow at least? Thanks in advance!

2

Answers


  1. What you are trying to do is impossible by design. You have to re-request the address view permission every time your page refreshes (for privacy reasons).

    Login or Signup to reply.
  2. u will stay connected on page refresh with these codes in react,next,next etc.

    import { useState, useEffect } from "react";
    
    export default function Home() {
      const [ismetamask, setIsmetamask] = useState(false); // is metamask installed ?
      const [accountaddress, setAccountaddress] = useState([]);
    
      useEffect(() => {
        if (window) {
          //sometimes window is not loaded, so wait for windows loading
          if (typeof window.ethereum !== "undefined") {
            console.log("MetaMask is installed!");
            setIsmetamask(true);
    
            // check if metamask is already connected
            if (window.ethereum._state.accounts.length > 0) {
              // metamask is already connected
              ethereum.request({ method: "eth_requestAccounts"});
              setAccountaddress(window.ethereum._state.accounts[0]);
            } else {
              // metamask not connected yet
            }
    
            // trigger when account change: logout or login
            ethereum.on("accountsChanged", function (accounts) {
            if (window.ethereum._state.accounts.length > 0) {
              setAccountaddress(window.ethereum._state.accounts[0]);
            }else{
              setAccountaddress([]);
            }
            });
          } else {
            console.log("metamask not installed");
          }
        } else {
          console.log("window not loaded yet");
        }
      }, []);
    
      const signinMetamask = async () => {
        // const accounts =
        await ethereum.request({ method: "eth_requestAccounts" });
        // const account = accounts[0];
      };
    
      return (
        <>
          {ismetamask ? (
            <>
              {accountaddress.length < 1 ? (
                <>
                  <button
                    onClick={() => {
                      signinMetamask();
                    }}
                    className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
                  >
                    Connect Metamask
                  </button>
                </>
              ) : (
                <>user: {accountaddress}</>
              )}
            </>
          ) : (
            <>metamask not installed</>
          )}
        </>
      );
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search