-
Notifications
You must be signed in to change notification settings - Fork 2
/
elm-ports-swclient.js
51 lines (44 loc) · 1.63 KB
/
elm-ports-swclient.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
var channel = new BroadcastChannel("sw-messages");
var ElmPortsSWClient = {
registration: null,
bind: function(app) {
app.ports.availabilityRequest.subscribe(() => {
var available = "serviceWorker" in navigator;
app.ports.availabilityResponse.send(available);
});
app.ports.registrationRequest.subscribe(() => {
navigator.serviceWorker.register("/service-worker.js").then(
registration => {
if (this.registration != null) {
console.log("I already have a registration :-(");
return;
}
this.registration = registration;
app.ports.registrationResponse.send("success");
},
err => {
app.ports.registrationResponse.send("error");
}
).catch(x => {
console.log(x);
});
});
navigator.serviceWorker.onmessage = event => {
app.ports.onMessageInternal.send(event.data);
};
app.ports.postMessageInternal.subscribe(msg => {
if (!this.registration.active) {
console.log("could not post msg: SW not active");
return;
}
var sw = this.registration.active;
sw.postMessage(msg);
});
channel.onmessage = event => {
app.ports.onMessageInternal.send(event.data);
};
app.ports.requestPermissionInternal.subscribe(() => {
Notification.requestPermission();
});
}
};