Skip to content

Service Worker

Service Worker 是在浏览器后台运行的脚本,可处理缓存、推送通知等任务。借助 Service Worker 适配器,可以让 Hono 应用作为浏览器中的 FetchEvent 处理器。

本页示例使用 Vite 创建项目。

1. 环境准备

首先创建项目目录并进入:

sh
mkdir my-app
cd my-app

创建 package.json

json
{
  "name": "my-app",
  "private": true,
  "scripts": {
    "dev": "vite dev"
  },
  "type": "module"
}

创建 tsconfig.json

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "WebWorker"],
    "moduleResolution": "bundler"
  },
  "include": ["./"],
  "exclude": ["node_modules"]
}

安装所需依赖。

sh
npm i hono
npm i -D vite
sh
yarn add hono
yarn add -D vite
sh
pnpm add hono
pnpm add -D vite
sh
bun add hono
bun add -D vite

2. Hello World

编辑 index.html

html
<!doctype html>
<html>
  <body>
    <a href="/sw">Hello World by Service Worker</a>
    <script type="module" src="/main.ts"></script>
  </body>
</html>

main.ts 用于注册 Service Worker:

ts
function register() {
  navigator.serviceWorker
    .register('/sw.ts', { 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 (const registration of registrations) {
        console.log('Unregister Service Worker')
        registration.unregister()
      }
      register()
    })
}
start()

sw.ts 中使用 Hono 构建应用,并通过 Service Worker 适配器的 handle 将其注册到 fetch 事件,这样访问 /sw 时便由 Hono 接管:

ts
// To support types
// https://github.com/microsoft/TypeScript/issues/14877
declare const self: ServiceWorkerGlobalScope

import { Hono } from 'hono'
import { handle } from 'hono/service-worker'

const app = new Hono().basePath('/sw')
app.get('/', (c) => c.text('Hello World'))

self.addEventListener('fetch', handle(app))

使用 fire()

fire() 会自动调用 addEventListener('fetch', handle(app)),让代码更简洁:

ts
import { Hono } from 'hono'
import { fire } from 'hono/service-worker'

const app = new Hono().basePath('/sw')
app.get('/', (c) => c.text('Hello World'))

fire(app)

3. 运行

启动开发服务器。

sh
npm run dev
sh
yarn dev
sh
pnpm run dev
sh
bun run dev

默认情况下,开发服务器运行在 5173 端口。访问 http://localhost:5173/ 完成 Service Worker 注册,然后访问 /sw 查看 Hono 应用的响应。

Released under the MIT License.