Skip to content

Instantly share code, notes, and snippets.

View oahehc's full-sized avatar

Andrew oahehc

View GitHub Profile
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
const promiseArr = cacheNames.map((item) => {
if (item !== CACHE_NAME) {
return caches.delete(item);
}
});
return Promise.all(promiseArr);
})
self.addEventListener("push", (event) => {
if (event.data) {
try {
data = JSON.parse(event.data.text());
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.content,
icon: "/icon-192.png",
badge: "/badge-192.png",
})
// Get permission & subscription
if (Notification && Notification.permission === "default") {
Notification.requestPermission().then((result) => {
if (result === "denied") {
return;
}
if (result === "granted") {
if (navigator && navigator.serviceWorker) {
navigator.serviceWorker.ready.then((reg) => {
self.addEventListener("updatefound", () => {
if (reg.installing) {
reg.installing.addEventListener("statechange", () => {
if (worker.state == "installed") {
// display a message to tell our users that
// there's a new service worker is installed
}
});
}
});
// send message to service worker
function handleClickEven() {
worker.postMessage({ action: "skipWaiting" });
}
// receive message
self.addEventListener("message", (event) => {
if (event.data.action === "skipWaiting") {
// skip waiting to apply the new version of service worker
self.skipWaiting();
self.addEventListener("fetch", (event) => {
// hijacking path and return a mock HTML content
if (event.request.url.includes("/faq")) {
event.respondWith(
new Response("<div>Mock FAQ Page</div>", {
headers: { "Content-Type": "text/html" },
})
);
}
// hijacking API request and return mock response in JSON format
const urlsToCache = ["/faq", "/contact"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(urlsToCache);
})
);
});
navigator.serviceWorker
.register("/sw.js")
.then((reg) => {
// no controller exist, page wasn't loaded via a service worker
if (!navigator.serviceWorker.controller) {
return;
}
if (reg.waiting) {
// If we have a new version of the service worker is waiting,
@oahehc
oahehc / closure.js
Created January 1, 2020 01:48
simple example for Javascript closure
function counter() {
let count = 1;
return function getCount() {
count++;
return count;
}
}
const getCountA = counter();
var now = new Date(); // Date object
now.toDateString() // "Sun Jul 17 2016"
now.toLocaleDateString() // "2016/7/17"
now.toGMTString() // "Sun, 17 Jul 2016 03:16:49 GMT"
now.toISOString() // "2016-07-17T03:16:49.141Z"
now.toUTCString() // "Sun, 17 Jul 2016 03:16:49 GMT"
now.toLocaleTimeString() // "上午11:16:49"
now.toLocaleString() // "2016/7/17 上午11:16:49"
now.toString() // "Sun Jul 17 2016 11:16:49 GMT+0800 (台北標準時間)"
now.toTimeString() // "11:16:49 GMT+0800 (台北標準時間)"