Skip to content

Instantly share code, notes, and snippets.

@semlinker
Created September 25, 2022 01:30
Show Gist options
  • Save semlinker/56567ddfb655634e341fc6093152c8f0 to your computer and use it in GitHub Desktop.
Save semlinker/56567ddfb655634e341fc6093152c8f0 to your computer and use it in GitHub Desktop.
Background Color Sync with BroadcastChannel API
<!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