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
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).
u will stay connected on page refresh with these codes in react,next,next etc.