-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
81 lines (70 loc) · 2 KB
/
sw.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
71
72
73
74
75
76
77
78
79
80
81
// import { Hono } from './hono.js'
import { Hono } from 'hono'
import { serveStatic } from './hono.serve-static.js'
import { logger } from './hono.logger.js'
let from
try {
from = FROM // "Server" is set on Cloudflare Workers environment variables
} catch {
from = 'Service Worker'
}
const app = new Hono()
// Middleware
app.use('/sw/*', logger())
app.use('/server/*', logger())
app.use('/:name{.+.js}', serveStatic({ root: './' }))
const script = `<script>
function register() {
navigator.serviceWorker.register('/sw.js', { scope: '/sw/', type: 'module' }).then(function(registration) {
console.log('Register Service Worker: Success');
}, function(error) {
console.log('Register Service Worker: Error');
});
}
function start() {
navigator.serviceWorker.getRegistrations().then(function(registrations) {
for(let registration of registrations) {
console.log('Unregister Service Worker');
registration.unregister();
}
register();
})
}
start();
</script>`
const header = `<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>pre { font-size: 2em; } body { padding: 2em; }</style>
</head><body>
<h1><a href="/">Service Worker Magic</a></h1>
<ul><li><a href="/server/hello">From Server</a></li>
<li><a href="/sw/hello">From Service Worker</a></li></ul>`
const footer = `
<footer>Server(Cloudflare Workers) and Browser(Service Worker) code are <a href="/sw.js">same</a>!</footer>
</body></html>`
// Top page
app.get('/', (c) => {
const html = `${header}
${script}
<pre>This is ${new URL(c.req.url).pathname}
Hello! from ${from}!
</pre><p><b>Registering Service Worker...</b></p>
${footer}
`
return c.html(html)
})
// Handler
const handler = (c) => {
const html = `${header}
<pre>This is ${new URL(c.req.url).pathname}
Hello! from ${from}!</pre>
${footer}
`
return c.html(html)
}
// Route
app.get('/server/hello', handler)
app.get('/sw/hello', handler)
app.get('/sw/jsx', handler)
// addEventListener('fetch'...
app.fire()