[HTML5] Implement JavaScript PWA update callbacks.

Allows detecting when a new version of the progressive web app service
worker is waiting (i.e. an update is pending), along a function to force
the update and reload all clients.
This commit is contained in:
Fabio Alessandrelli 2022-01-31 15:28:12 +01:00
parent 3cc72ac03f
commit 948e66c3d6
8 changed files with 119 additions and 0 deletions

View file

@ -368,3 +368,58 @@ const GodotEventListeners = {
},
};
mergeInto(LibraryManager.library, GodotEventListeners);
const GodotPWA = {
$GodotPWA__deps: ['$GodotRuntime', '$GodotEventListeners'],
$GodotPWA: {
hasUpdate: false,
updateState: function (cb, reg) {
if (!reg) {
return;
}
if (!reg.active) {
return;
}
if (reg.waiting) {
GodotPWA.hasUpdate = true;
cb();
}
GodotEventListeners.add(reg, 'updatefound', function () {
const installing = reg.installing;
GodotEventListeners.add(installing, 'statechange', function () {
if (installing.state === 'installed') {
GodotPWA.hasUpdate = true;
cb();
}
});
});
},
},
godot_js_pwa_cb__sig: 'vi',
godot_js_pwa_cb: function (p_update_cb) {
if ('serviceWorker' in navigator) {
const cb = GodotRuntime.get_func(p_update_cb);
navigator.serviceWorker.getRegistration().then(GodotPWA.updateState.bind(null, cb));
}
},
godot_js_pwa_update__sig: 'i',
godot_js_pwa_update: function () {
if ('serviceWorker' in navigator && GodotPWA.hasUpdate) {
navigator.serviceWorker.getRegistration().then(function (reg) {
if (!reg || !reg.waiting) {
return;
}
reg.waiting.postMessage('update');
});
return 0;
}
return 1;
},
};
autoAddDeps(GodotPWA, '$GodotPWA');
mergeInto(LibraryManager.library, GodotPWA);