Skip to content

Instantly share code, notes, and snippets.

@raubin-kumar
Last active October 7, 2021 13:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raubin-kumar/4a34d14d5240ddde757567a7d20529ac to your computer and use it in GitHub Desktop.
Save raubin-kumar/4a34d14d5240ddde757567a7d20529ac to your computer and use it in GitHub Desktop.
Service worker files
//service-worker.js
const cacheVersion = 'v1';
self.addEventListener('activate', function (event) {
event.waitUntil(
caches.keys().then(function (cacheNames) {
cacheNames.map(function (cacheName) {
if (cacheName.indexOf(cacheVersion) < 0) {
return caches.delete(cacheName);
}
});
}).then(function () {
setupIndexDB()
})
)
})
// Set up a channel
const broadcast = new BroadcastChannel("upload-channel");
// Listen to message
broadcast.onmessage = (event) => {
if (event.data && event.data.type === "NOTIFY") {
//Notify user.
}
};
//When network is online, retry upload.
window.addEventListener("online", () => {
// Post message to service worker
broadcast.postMessage({
type: "RETRY_UPLOAD",
});
})
//service-worker.js
// Set up channel with same name
const broadcast = new BroadcastChannel("upload-channel");
broadcast.onmessage = (event) => {
if (event.data && event.data.type === "RETRY_UPLOAD ") {
retryFailedUploads().then(() => {
broadcast.postMessage({type: " NOTIFY"});
})
}
};
//service-worker.js
self.addEventListener("fetch", function (event) {
event.respondWith(
caches.match(event.request).then(function (response) {
// caches.match() will always resolve with success if match or undefined if no cache
if (response !== undefined) {
return response;
} else {
return fetch(event.request)
.then(function (response) {
//cache the response so that can be used next time
let responseClone = response.clone();
caches.open("page_cache-v1").then(function (cache) {
cache.put(event.request, responseClone);
});
return response;
})
.catch(function () {
//Handle error.
});
}
})
);
});
//Create instance of message channel. Message channel instance contains two ports port1 and port2
const messageChannel = new MessageChannel();
// Initialize channel port.
//Second parameter to the post message is transfer ownership of channel port.
navigator.serviceWorker.controller.postMessage({
type: "SET_CHANNEL_PORT",
}, [messageChannel.port2]);
// Listen to the message from service worker
messageChannel.port1.onmessage = (event) => {
if (event.data && event.data.type === "NOTIFY") {
//Notify User
}
};
//When network is online, retry upload.
window.addEventListener("online", () => {
// Post message to service worker
broadcast.postMessage({
type: "RETRY_UPLOAD",
});
});
//service-worker.js
let channelPort;
self.addEventListener("message", event => {
if (event.data && event.data.type === "SET_CHANNEL_PORT") {
channelPort = event.ports[0];
}
if (event.data && event.data.type === "RETRY_UPLOAD") {
retryFailedUploads().then(() => {
channelPort.postMessage({ TYPE: "NOTIFY" });
});
}
})
//Listen to messages from service worker
navigator.serviceWorker.onmessage = (event) => {
if (event.data && event.data.type === "NOTIFY") {
//Notify user.
}
};
//When network is online, retry upload.
window.addEventListener("online", () => {
// Post message to service worker
broadcast.postMessage({
type: "RETRY_UPLOAD",
});
});
//service-worker.js
//Liten to message from client
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "RETRY_UPLOAD") {
retryFailedUploads().then(() => {
// Send a response to client.
self.clients
.matchAll({
includeUncontrolled: true, //All serivce worker clients will be returned
})
.then((clients) => {
if (clients && clients.length) {
//All clients are ordered by last focused.
clients[0].postMessage({
type: "NOTIFY",
});
}
});
});
}
})
//service-worker.js
self.addEventListener("install", function (event) {
event.waitUntil(
caches.open("page_cache-v1").then(function (cache) {
return cache.addAll([
//Paths to cache
/css/main.css',
'/js/main.js',
'/index.html'
]);
})
);
});
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/service-worker.js").then(
function (registration) {
//Do stuffs on success
},
function (err) {
//Do stuffs on failure
}
);
});
}
const saveFormData = (formData) => {
fetch("/api/data/save", { method: "POST", body: JSON.stringify(formData) })
.then((resp) => {
//Notify user
})
.catch((err) => {
//store data to indexed db for retry // Say Network was offline for simplicity.
saveDataToIndexedDB();
});
};
const saveFormData = (formData) => {
fetch("/api/data/save", { method: "POST", body: JSON.stringify(formData) })
.then((resp) => {
//Notify user
})
.catch((err) => {
//store data to indexed db for retry // Say Network was offline for simplicity.
saveDataToIndexedDB();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment