Created
September 25, 2022 01:30
-
-
Save semlinker/56567ddfb655634e341fc6093152c8f0 to your computer and use it in GitHub Desktop.
Background Color Sync 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>Background Color Sync with BroadcastChannel API</title> | |
</head> | |
<body> | |
<input type="color" id="bgColorPicker" /> | |
<script> | |
(() => { | |
const bc = new BroadcastChannel("bytefer_channel"); | |
const bodyElement = document.querySelector("body"); | |
const bgColorPicker = document.querySelector("#bgColorPicker"); | |
const COLOR_KEY = "bgColor"; | |
const setBackgroundColor = (color) => { | |
bodyElement.style.backgroundColor = color; | |
}; | |
bc.onmessage = (messageEvent) => { | |
if (messageEvent.data === "updateBgColor") { | |
const bgColor = localStorage.getItem(COLOR_KEY); | |
bgColorPicker.value = bgColor; | |
setBackgroundColor(bgColor); | |
} | |
}; | |
if (localStorage.getItem(COLOR_KEY)) { | |
setBackgroundColor(localStorage.getItem(COLOR_KEY)); | |
} else { | |
alert("Please choose a background color."); | |
} | |
bgColorPicker.onchange = (e) => { | |
const bgColor = e.target.value; | |
localStorage.setItem(COLOR_KEY, bgColor); | |
setBackgroundColor(bgColor); | |
bc.postMessage("updateBgColor"); | |
}; | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment