Skip to content

Instantly share code, notes, and snippets.

@enrico-atzeni
Last active January 12, 2022 14:37
Show Gist options
  • Save enrico-atzeni/eb272cb72e91f0d8b78fea4418782b66 to your computer and use it in GitHub Desktop.
Save enrico-atzeni/eb272cb72e91f0d8b78fea4418782b66 to your computer and use it in GitHub Desktop.
A simple (and very basic) javascript snippet to auto refresh, forcing a new file fetch (ignoring browser cache) for lovelace card images. Put this file into config/www folder and load in into your dashboard using frontend: extra_module_url setting in the main configuration.yml file
(function(){
function getShadowRoots(wrap) {
if (!wrap) return [];
var found = [];
var els = wrap.querySelectorAll('*');
for (var i=0; i < els.length; i++) {
if (els[i].shadowRoot) found.push(els[i].shadowRoot);
}
return found;
}
function findImagesInWrap(wrap) {
var roots = getShadowRoots(wrap);
var imgs = [];
for (var i=0; i < roots.length; i++) {
imgs.push(...roots[i].querySelectorAll('img'));
imgs.push(...findImagesInWrap(roots[i]));
}
return imgs;
}
function updater() {
var root = document.querySelector('body > home-assistant').shadowRoot.querySelector('*').shadowRoot.querySelector('app-drawer-layout partial-panel-resolver ha-panel-lovelace').shadowRoot.querySelector('hui-root').shadowRoot.querySelector('#layout hui-masonry-view').shadowRoot;
//console.log("ROOT ",root);
if (!root) return;
var imgs = findImagesInWrap(root);
// console.log("Imgs found: ",imgs);
var k = 'lciu_random=';
var random = new Date().getTime();
for (var i=0; i < imgs.length; i++) {
var newSrc = "";
if (imgs[i].src.indexOf('/local')) {
if (imgs[i].src.indexOf(k) !== -1) {
newSrc = imgs[i].src.replace(k, k+random);
} else {
var sep = '?';
if (imgs[i].src.indexOf("?") !== -1) {
sep = '&';
}
newSrc = imgs[i].src + sep + k+random;
}
}
if (newSrc !== "") {
imgs[i].setAttribute("src", newSrc);
// console.log("Updated image ",imgs[i].src, newSrc);
}
}
}
// twice per minute
window.ich = setInterval(updater, 1000 * 30);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment