Created
September 25, 2022 02:46
-
-
Save semlinker/57ebac9d3f80d888d5fb0391bad32d08 to your computer and use it in GitHub Desktop.
Synchronized login status with BroadcastChannel API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Synchronized login status with BroadcastChannel API</title> | |
</head> | |
<body> | |
<h3>Current status: <span id="status">signed in</span></h3> | |
<button id="btn" onclick="toggleStatus()">Log out</button> | |
<script> | |
const status = document.querySelector("#status"); | |
const btn = document.querySelector("#btn"); | |
const logoutChannel = new BroadcastChannel("logout_channel"); | |
let currentStatus = "signedIn"; | |
logoutChannel.onmessage = function (e) { | |
if (e.data.cmd === "logout") { | |
logout(); | |
btn.innerText = "Sign in"; | |
} else if (e.data.cmd === "signedIn") { | |
signedIn(); | |
btn.innerText = "Log out"; | |
} | |
}; | |
function toggleStatus() { | |
if (currentStatus === "signedIn") { | |
logout(); | |
logoutChannel.postMessage({ cmd: "logout" }); | |
} else { | |
signedIn(); | |
logoutChannel.postMessage({ cmd: "signedIn", user: "Bytefer" }); | |
} | |
} | |
function logout() { | |
currentStatus = "logout"; | |
status.innerText = "logged out"; | |
btn.innerText = "Sign in"; | |
} | |
function signedIn() { | |
currentStatus = "signedIn"; | |
status.innerText = "singed in"; | |
btn.innerText = "Log out"; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment