Skip to content

Instantly share code, notes, and snippets.

@pepelsbey
Last active November 18, 2016 21:38
Show Gist options
  • Save pepelsbey/9a6952b0e5b6e964f85107aec90a6241 to your computer and use it in GitHub Desktop.
Save pepelsbey/9a6952b0e5b6e964f85107aec90a6241 to your computer and use it in GitHub Desktop.
importScripts('idb-keyval.js');
const VERSION = 'v1';
self.addEventListener('install', function (e) {
self.skipWaiting();
e.waitUntil(
caches.open(VERSION).then(function (cache) {
return cache.addAll([
'./',
'./index.html',
'../style.css',
'enhanced.js'
]);
})
);
});
self.addEventListener('fetch', function (e) {
let request = e.request;
if (request.method !== 'GET') {
return;
}
});
self.addEventListener('activate', function () {
if (self.clients && clients.claim) {
clients.claim();
}
});
self.addEventListener('sync', function (e) {
if (e.tag == 'form-post') {
e.waitUntil(postComment());
}
});
function postComment () {
let formData = new FormData();
idbKeyval.get('name').then(function (data) {
formData.append('name', data);
});
idbKeyval.get('comment').then(function (data) {
formData.append('comment', data);
});
fetch('./save', {
method: 'POST',
mode: 'cors',
body: formData
}).then(function (response) {
return response;
}).then(function (text) {
send_message_to_all_clients('success');
}).catch(function (error) {
send_message_to_all_clients('error');
});
}
function send_message_to_client (client, msg) {
return new Promise(function (resolve, reject) {
var msg_chan = new MessageChannel();
msg_chan.port1.onmessage = function (e) {
if (e.data.error) {
reject(e.data.error);
} else {
resolve(e.data);
}
};
client.postMessage(msg, [msg_chan.port2]);
});
}
function send_message_to_all_clients (msg) {
clients.matchAll().then(clients => {
clients.forEach(client => {
send_message_to_client(client, msg).then(
msg => console.log('Сообщение из сервис-воркера: ' + msg)
);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment