-
Notifications
You must be signed in to change notification settings - Fork 9
/
page.js
54 lines (47 loc) · 1.53 KB
/
page.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
'use strict';
var atoa = require('atoa');
var serialization = require('./serialization');
var emitter = require('contra/emitter');
module.exports = createChannel;
function createChannel () {
var channel = at(navigator.serviceWorker.controller);
return channel;
function at (worker) {
var internalEmitter = emitter();
var api = {
on: selfed('on'),
once: selfed('once'),
off: selfed('off'),
emit: postToWorker,
at: at
};
var postFromWorker = serialization.emission(internalEmitter, { broadcast: false });
navigator.serviceWorker.addEventListener('message', broadcastHandler);
return api;
function selfed (method) {
return function selfish () {
internalEmitter[method].apply(null, arguments);
return api;
};
}
function postToWorker () {
if (!worker) {
return Promise.reject(new Error('ServiceWorker not found.'));
}
var payload = serialization.parsePayload(atoa(arguments));
var messageChannel = new MessageChannel();
messageChannel.port1.addEventListener('message', postFromWorker);
messageChannel.port1.start();
return worker.postMessage(payload, [messageChannel.port2]);
}
function broadcastHandler (e) {
if (e.source !== worker) {
return; // ignore broadcast messages from other workers than the one we're talking to.
}
var data = e.data;
if (data && data.__broadcast) {
serialization.emission(internalEmitter, { broadcast: true })(e);
}
}
}
}