Skip to content

Instantly share code, notes, and snippets.

@devsnek
Last active September 24, 2021 04:28
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 devsnek/fe2524a6981377567648a4f1da6813d0 to your computer and use it in GitHub Desktop.
Save devsnek/fe2524a6981377567648a4f1da6813d0 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<script src="index.js"></script>
</html>
'use strict';
/* eslint-env browser */
async function ready() {
const sw = globalThis.navigator.serviceWorker;
const registration = await sw.getRegistration();
sw.addEventListener('message', ({ data: { id, data } }) => {
registration.active.postMessage({ id, data: eval(data) });
});
globalThis.worker = new Worker('./web-worker.js');
}
navigator.serviceWorker.register('./service-worker.js')
.then((registration) => {
if (registration.active) {
ready();
} else {
registration.installing.addEventListener('statechange', (event) => {
if (event.target.state === 'activated') {
ready();
}
});
}
});
'use strict';
/* eslint-env browser */
self.addEventListener('install', () => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
const requests = new Map();
let idCounter = 0;
async function proxyMessage(request) {
const id = idCounter;
idCounter += 1;
const clients = await self.clients.matchAll({ type: 'window' });
clients[0].postMessage({ id, data: request });
return new Promise((resolve, reject) => {
requests.set(id, { resolve, reject });
});
}
self.addEventListener('message', ({ data: { id, data } }) => {
requests.get(id).resolve(data);
requests.delete(id);
});
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (event.request.method === 'POST' && url.pathname === '/_proxy') {
event.respondWith((async () => {
const body = await event.request.json();
const response = await proxyMessage(body);
return new Response(JSON.stringify(response), {
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
},
});
})());
}
});
'use strict';
/* eslint-env browser */
function sync(data) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/_proxy', false);
xhr.send(JSON.stringify(data));
return JSON.parse(xhr.responseText);
}
self.addEventListener('message', ({ data }) => {
console.log(sync(data));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment