Skip to content

Instantly share code, notes, and snippets.

@andrejilderda
Last active May 29, 2025 19:09
Show Gist options
  • Save andrejilderda/f6673f1b1a986b2dc0cd01607acbff26 to your computer and use it in GitHub Desktop.
Save andrejilderda/f6673f1b1a986b2dc0cd01607acbff26 to your computer and use it in GitHub Desktop.
// Option 1: Refresh on window focus
function onVisibilityChange(callback) {
let visible = true;
const focused = () => {
if (!visible) callback((visible = true));
};
const unfocused = () => {
if (visible) callback((visible = false));
};
window.onfocus = focused;
window.onblur = unfocused;
}
function updateCSSOnFocus(url) {
function handleFocusChange(_visible) {
const $injectedCSS = document.querySelector("#injectedCSS");
if ($injectedCSS) {
return ($injectedCSS.href = `${url}?last-reload=${Date.now()}`);
} else {
document.body.insertAdjacentHTML(
"beforeend",
`<link rel="stylesheet" id="injectedCSS" href="${url}">`
);
}
}
onVisibilityChange(handleFocusChange);
handleFocusChange();
}
updateCSSOnFocus("http://localhost:8080/macos-theme-for-joplin.css");
// Option 2: Auto-refresh Every 2 Seconds
function autoRefreshCSS(url, interval = 2000) {
function updateCSS() {
const $injectedCSS = document.querySelector("#injectedCSS");
if ($injectedCSS) {
$injectedCSS.href = `${url}?last-reload=${Date.now()}`;
} else {
document.body.insertAdjacentHTML(
"beforeend",
`<link rel="stylesheet" id="injectedCSS" href="${url}">`
);
}
}
updateCSS(); // Initial load
return setInterval(updateCSS, interval);
}
const refresher = autoRefreshCSS(
"http://localhost:8080/macos-theme-for-joplin.css"
);
// To stop: clearInterval(refresher);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment