Hello everybody,
Please i need help in this code, even if i signed to metamask using button ( Sign with Metamask ) and i refresh the page it always still connected and i should click on logout button
what i want to do
1 - when you refresh the page it logout automatically.
2 - display logout button only if it is signed in
and thank you in advance!
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
<script src="https://unpkg.com/moralis/dist/moralis.js"></script>
<title>Metamask Login</title>
</head>
<body>
<h1>Login with metamask :</h1>
<button id="login">Login with Metamask</button>
<button id="logout">Logout</button>
<script>
//Connect SDK MORALIS
const serverUrl = "https://jt9kvea7eitk.usemoralis.com:2053/server";
const appId = "2FE0jmEybp6PgKfbetNpzq8BoTNF8f4uQgDd2xY5";
Moralis.start({ serverUrl, appId });
//Login function
async function login() {
let user = Moralis.User.current();
if (!user) {
try {
user = await Moralis.authenticate({ signingMessage: "Hello World!" })
document.getElementById('login').innerHTML = user.get('ethAddress')
document.getElementById('logout').style.display = "block"
} catch(error) {
console.log(error)
}
}
}
//Logout function
async function logOut() {
await Moralis.User.logOut();
document.getElementById('logout').style.display = "none"
document.getElementById('login').innerHTML = "Login with Metamask"
}
document.getElementById("login").onclick = login;
document.getElementById("logout").onclick = logOut;
</script>
</body>
</html>