Sitecore JSS and PWA

{
"theme_color": "#e5f2f6",
"background_color": "#3399B6",
"display": "standalone",
"scope": "/myapp1",
"start_url": "/myapp1",
"name": "Domain - myapp1",
"short_name": "myapp1",
"icons": [
{
"src": "img/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
}, {
"src": "img/icon-256x256.png",
"sizes": "256x256",
"type": "image/png"
}, {
"src": "img/icon-384x384.png",
"sizes": "384x384",
"type": "image/png"
}, {
"src": "img/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}]
}
const isLocal = Boolean(window.location.hostname === "localhost");
export function register(config) {
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
registerValidSW(config);
});
}
}
function registerValidSW(config) {
const serviceWorkUrl = isLocal ? "/sw.js" : "/dist/myapp/sw.js";
navigator.serviceWorker
.register(serviceWorkUrl)
.then((registration) => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log("New content is available and will be used when all " + "tabs for this page are closed. See https://bit.ly/CRA-PWA."
);
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message
console.log("Content is cached for offline use.");
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
};
};
})
.catch((error) => {
console.error("Error during service worker registration:", error);
});
}
export function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready
.then((registration) => {
registration.unregister();
}).catch((error) => {
console.error(error.message);
});
}
}
const CACHE = "myapp:V1";
const isLocal = Boolean(self.location.hostname === "localhost");
const offlineFallbackPage = isLocal ? "index.html" : "/myapp1";
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING")
self.skipWaiting();
}
});
self.addEventListener("install", async (event) => {
event.waitUntil(
caches.open(CACHE).then((cache) => {
cache.addAll(["index.html", "main.css", "favicon.ico"]);
})
);
});
self.addEventListener("fetch", (event) => {
if (event.request.mode === "navigate") {
event.respondWith(
(async () => {
try {
const preloadResp = await event.preloadResponse;
if (preloadResp) {
return preloadResp;
}
const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {
const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})()
);
}
});
import * as serviceWorker from "./serviceWorker";
....
serviceWorker.register();
public class ServiceWorkerHostController : ApiController
{
[HttpGet, Route("myapp1/sw.js")]
public HttpResponseMessage ServiceWorkerHost()
{
var contents = GetFileContents("~/dist/myapp1/sw.js");
return GetResponse(contents, "application/javascript");
}
[HttpGet, Route("myapp1/manifest.json")]
public HttpResponseMessage ManifestHost()
{
var contents = GetFileContents("~/dist/myapp1/manifest.json");
return GetResponse(contents, "application/json");
}
private HttpResponseMessage GetResponse(byte[] contents, string contentType)
{
var httpResponseMessage = request.CreateResponse(HttpStatusCode.OK);
httpResponseMessage.Content = new ByteArrayContent(contents);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
return httpResponseMessage;
}
private byte[] GetFileContents(string path)
{
var swPath = HostingEnvironment.MapPath(path);
return File.ReadAllBytes(swPath);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Joris Visser

Joris Visser

Sitecore developer, mostly working on unique solution