I ran into a caching issue after switching to the PWA template, it was caching the old version of my game, even if I turned all caching off for the web server.
It seems the service worker caches itself and then servers the old version to the client.
Is this a bug or is there something I’m missing?
Im also experiencing this issue. I’ve tried with name files as hash but it didn’t fix it. Did you manage to find a solution?
This is how I fixed it:
#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEditor.Callbacks;
public class FixPWA {
[PostProcessBuild(1)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) {
FixIndex(pathToBuiltProject);
FixServiceWorker(pathToBuiltProject);
}
public static void FixIndex(string path) {
path = $"{path}/index.html";
if (!File.Exists(path)) return;
var index = File.ReadAllText(path);
if (index.Contains("register(\"ServiceWorker.js\").")) return;
// Fix title
index = index.Replace("Unity WebGL Player | ", "");
// Prompt user to reload new version
index = index.Replace("register(\"ServiceWorker.js\");",
@"register('ServiceWorker.js').then(reg => {
reg.onupdatefound = () => {
const installingWorker = reg.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed' && navigator.serviceWorker.controller) {
if (confirm('An update is available, do you want to reload?')) {
location.reload();
}
}
};
};
});");
File.WriteAllText(path, index);
}
public static void FixServiceWorker(string path) {
path = $"{path}/ServiceWorker.js";
if (!File.Exists(path)) return;
var sw = File.ReadAllText(path);
if (sw.Contains("skipWaiting")) return;
// Don't cache ServiceWorker.js
sw = sw.Replace(
"self.addEventListener('fetch', function (e) {",
@"self.addEventListener('fetch', function (e) {
if (e.request.url.endsWith('/ServiceWorker.js')) { return }
");
// Don't wait
sw = sw.Replace(
"console.log('[Service Worker] Install');",
@"console.log('[Service Worker] Install');
self.skipWaiting();");
// Clear old cache
sw = sw.Replace(
"e.waitUntil((async function () {",
@"e.waitUntil((async function () {
for (let name of (await caches.keys()))
caches.delete(name);
");
File.WriteAllText(path, sw);
}
}
#endif