Skip to content

Instantly share code, notes, and snippets.

@kawazoe
Last active February 1, 2024 06:50
Show Gist options
  • Save kawazoe/fa3b5a3c998d16871ffb9e2fd721cb4b to your computer and use it in GitHub Desktop.
Save kawazoe/fa3b5a3c998d16871ffb9e2fd721cb4b to your computer and use it in GitHub Desktop.
Auto refresh page on manifest.json change. iOS offline PWA hack to handle auto updates.
// ------------------------------------------- IMPORTANT -------------------------------------------
// This is a development file to be minified using https://javascript-minifier.com/ and inlined in
// the index.html file. This file is not compiled or processed by webpack so it should be treated as
// low-level precompiled es5-compatible javascript. The code here is not meant to be clean, it's
// meant to be as light and fast as possible since it runs in the head tag.
// HACK: This file a hack to ensure that home-screen apps on mobile devices gets refreshed when they
// start. It works by forcing a load of the service-worker.js file and use the precache-manifest
// file name as an application version, just like a desktop browser like chrome would do. When
// when it detects a change in the application version, it reloads the page and bypass the browser's
// cache. This should force mobile devices to reload the new version of the app even if they cached
// an older version of the site.
(function () {
var r = new XMLHttpRequest();
r.onload = function () {
var t = r.responseText;
var versionStart = t.indexOf('"/precache-manifest.') + 20;
var versionEnd = t.indexOf('.js"', versionStart);
if (versionEnd - versionStart === 32) {
var ls = localStorage;
var oldPrecacheManifestVersion = ls.getItem('pmv');
var newPrecacheManifestVersion = t.substring(versionStart, versionEnd);
if (newPrecacheManifestVersion !== oldPrecacheManifestVersion) {
ls.setItem('pmv', newPrecacheManifestVersion);
return window.location.reload(true);
}
}
};
r.open('GET', '/service-worker.js?c=' + new Date().getTime());
r.setRequestHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
r.send();
}());
<script type="application/javascript">!function(){var e=new XMLHttpRequest;e.onload=function(){var n=e.responseText,t=n.indexOf('"/precache-manifest.')+20,o=n.indexOf('.js"',t);if(o-t==32){var r=localStorage,i=r.getItem("pmv"),s=n.substring(t,o);if(s!==i)return r.setItem("pmv",s),window.location.reload(!0)}},e.open("GET","/service-worker.js?c=" + new Date().getTime()),e.setRequestHeader('Cache-Control', 'no-cache, no-store, must-revalidate'),e.send()}();</script>
@kawazoe
Copy link
Author

kawazoe commented Oct 26, 2019

@alexeigs That is right. As far as I am aware off, the only way to reliably force an update in this case is to clear safari's cache. I have seen this cache survive OS updates so I wouldn't count on this happening by itself too much.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment