Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/yusukebe/service-worker-magic
Server and Browser code are really the same. It's magic.
https://github.com/yusukebe/service-worker-magic
Last synced: 2 days ago
JSON representation
Server and Browser code are really the same. It's magic.
- Host: GitHub
- URL: https://github.com/yusukebe/service-worker-magic
- Owner: yusukebe
- Created: 2022-02-10T15:56:58.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2023-10-20T05:02:13.000Z (about 1 year ago)
- Last Synced: 2024-11-01T13:34:14.191Z (9 days ago)
- Language: JavaScript
- Homepage: https://service-worker-magic.yusukebe.workers.dev/
- Size: 17.6 KB
- Stars: 36
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Service Worker Magic
- Server (Cloudflare Workers) code is [`sw.js`](./src/sw.js).
- Browser ( Service Worker ) code is [`sw.js`](./src/sw.js).
- Cloudflare Workers [`sw.js`](./src/sw.js) serves [`sw.js`](./src/sw.js).
- Service Worker [`sw.js`](./src/sw.js) will be registered on `/`. The scope is `/sw/*`.
- `/server/hello` => from the server.
- `/sw/hello` => from the browser not from a server. Request is intercepted by Service Worker.It's magic.
## Demo
-
## Screencast
![SS](https://user-images.githubusercontent.com/10682/153455595-77fea6e5-93d7-4698-8d75-85896edd995b.gif)
## Walkthrough
### Server
Run Cloudflare Workers on your terminal:
```sh
$ wrangler dev sw.js
````sw.js` is served by `sw.js`.
### Browser
Access `/`. Your browser will load `sw.js`:
```js
navigator.serviceWorker.register('/sw.js', { scope: '/sw/', type: 'module' })
```Service Worker is registered.
### Then...
- `/server/hello` => content is returned from the server.
- `/sw/hello` => content is returned from the browser. Not from the server.### Attention
If Service Worker does not work, clear the cache on your browser.
## Code
Just [`sw.js`](./src/sw.js).
### Short version
It does not work well.
```js
import { Hono } from './hono.js'
import { serveStatic } from './hono.serve-static.js'
import { logger } from './hono.logger.js'let from = 'Service Worker'
try {
from = FROM // "Server" is set on Cloudflare Workers environment variables
}const app = new Hono()
// Middleware
app.use('/sw/*', logger())
app.use('/server/*', logger())
app.use('/:name{.+.js}', serveStatic({ root: './' }))// Top page
app.get('/', (c) => {
const html = `
navigator.serviceWorker.register('/sw.js', { scope: '/sw/', type: 'module' })
`
return c.html(html)
})// Handler
const handler = (c) => {
const text = `Hello! from ${from}!`
return c.text(text)
}// Route
app.get('/server/hello', handler)
app.get('/sw/hello', handler)// addEventListener('fetch'...
app.fire()
```## Related projects
`sw.js` is using Hono as Service Worker framework.
- Hono\[炎\]
## Author
Yusuke Wada
## License
MIT