server : remove the built-in UI's service worker when the UI is not served (#29565)

With --path or --no-ui, /sw.js returned 404, and a 404 does not remove a service worker, so browsers kept showing the cached built-in UI. Serve a worker that unregisters itself, clears its caches and reloads open tabs. A sw.js in the --path folder is still served first.

Assisted-by: Claude Opus 5.5
This commit is contained in:
Emanuil Rusev
2026-09-29 17:48:17 +02:00
committed by GitHub
parent 00af63567a
commit ba0ba54d93
+17
View File
@@ -470,6 +470,23 @@ bool server_http_context::init_listener(const common_params & params) {
#endif
}
}
// a browser that used the built-in UI keeps its service worker, so it shows the old UI even after the UI is replaced or disabled
// answer the worker's update check with a worker that removes itself; a sw.js in public_path is served first
if (!params.ui || !params.public_path.empty()) {
srv->Get(params.api_prefix + "/sw.js", [](const httplib::Request &, httplib::Response & res) {
static constexpr const char * sw_remove_js = R"(
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => e.waitUntil((async () => {
await self.registration.unregister();
for (const key of await caches.keys()) await caches.delete(key);
for (const c of await self.clients.matchAll({ type: 'window' })) c.navigate(c.url);
})()));
)";
res.set_header("Cache-Control", "no-cache");
res.set_content(sw_remove_js, "application/javascript");
});
}
return true;
}