-
Notifications
You must be signed in to change notification settings - Fork 11
/
example.js
70 lines (66 loc) · 2.08 KB
/
example.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
59
60
61
62
63
64
65
66
67
68
69
70
var html = require('choo/html')
var log = require('choo-log')
var choo = require('choo')
var sw = require('.')
var clear = require('./clear')
var app = choo()
if (process.env.NODE_ENV !== 'production') {
app.use(clear())
}
app.use(sw())
app.use(log())
app.use(ready)
app.route('/', mainView)
app.mount('body')
function mainView (state, emit) {
return html`
<body>
<h1>Choo service worker example</h1>
<hr>
<div>
<p>syncTags: <b>${JSON.stringify(state.syncTags)}</b></p>
</div>
<p>To run this example, you must follow the next instructions (some of them will change some of the data above)</p>
<ol>
<li>Active notifications for this site <button onclick="${activeNotifications}">active notifications</button></li>
<li>Post a message <input id="message" type="text"/> <button onclick="${postMessage}">send</button></li>
<li>Get a message from worker <button onclick="${getMessage}">get message</button> <span id="worker-message"></span></li>
<li>Activate background syncronization <button onclick="${activateSync}">activate</button></li>
</ol>
</body>
`
function activeNotifications (e) {
e.preventDefault()
emit('render')
emit(sw.events.NOTIFICATION_REQUEST, function (result) {
emit('log:info', result)
})
}
function activateSync (e) {
e.preventDefault()
emit('render')
emit(sw.events.SYNC, 'test-tag')
}
function postMessage (e) {
e.preventDefault()
emit('render')
var message = document.getElementById('message').value
emit(sw.events.POST_MESSAGE, message)
}
function getMessage (e) {
e.preventDefault()
emit('render')
emit(sw.events.POST_MESSAGE, 'ping')
}
}
function ready (state, emitter) {
emitter.on(sw.events.MESSAGE, function (message) {
var span = document.getElementById('worker-message')
span.textContent = JSON.stringify(message)
// the service worker say that we should re render
if (message.data === 'render') {
emitter.emit('log:info', 'Re render from the service worker')
emitter.emit('render')
}
})
}