OLD | NEW |
---|---|
(Empty) | |
1 // Note: This JS can run either in a worker or as a script in the main document | |
2 // context. | |
3 function connectWebSocket(url, inWorker) { | |
4 function messageMainContext(data) { | |
5 if (inWorker) | |
6 self.postMessage(data); | |
7 else | |
8 self.postMessage(data, location); | |
9 } | |
10 var ws = new WebSocket(url); | |
11 | |
12 ws.onopen = function() { | |
13 ws.send('hello world'); | |
14 }; | |
15 | |
16 ws.onclose = function() { | |
17 messageMainContext('onclose'); | |
18 }; | |
19 | |
20 ws.onmessage = function() { | |
21 messageMainContext('onmessage'); | |
22 }; | |
23 } | |
24 | |
25 self.addEventListener('message', function(e) { | |
26 // Will only receive a message with a URL in it if this JS is executing in a | |
engedy
2017/03/06 16:31:01
To make this a bit cleaner, what do you think of:
Charlie Harrison
2017/03/06 19:22:11
SGTM. Done
| |
27 // worker. | |
28 if (e.data.url) { | |
29 connectWebSocket(e.data.url, true /* inWorker */); | |
30 } | |
31 }); | |
32 | |
OLD | NEW |