-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.js
58 lines (53 loc) · 1.68 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"use strict";
import { PeerPlugin, CachePlugin } from "/peer-cdn/index.es.js"; // from "peer-cdn";
if ("serviceWorker" in navigator) {
// since sw does not support WebRTC yet
// this is workaround to use it
// we use PeerPlugin on client side
const peerPlugin = new PeerPlugin({
cacheName: CachePlugin.peerFetch + 1,
timeoutAfter: 3000,
servers: {
iceServers: [
{
url: "stun:74.125.142.127:19302",
},
],
},
constraints: {
ordered: true,
},
});
// Set up a listener for messages posted from the service worker.
// The service worker is set to post a message to specific client only
// so you should see this message event fire once.
// You can force it to fire again by visiting this page in an Incognito window.
navigator.serviceWorker.addEventListener("message", function (event) {
const request = new Request(event.data.url);
// mock sw event wrapping request with object
const middleware = peerPlugin.getMiddleware({ request });
// run get method of a created middleware
middleware
.get()
.then(function (response) {
// return response to a service worker
event.ports[0].postMessage(response);
})
.catch(function (error) {
// return response to a service worker
event.ports[0].postMessage(null);
});
});
navigator.serviceWorker
.register("sw.js")
.then(function (registration) {
// Registration was successful
console.log(
"ServiceWorker registration successful with scope: ",
registration.scope
);
})
.catch(function (error) {
console.error("Service Worker Error", error);
});
}