Skip to content

Service Worker

Service Worker 是在浏览器后台运行的脚本,用于处理缓存和推送通知等任务。使用 Service Worker 适配器,你可以在浏览器中将使用 Hono 创建的应用作为 FetchEvent 处理程序运行。

此页面展示了使用 Vite 创建项目的示例。

🌐 This page shows an example of creating a project using Vite.

1. 设置

🌐 1. Setup

首先,创建并移动到你的项目目录:

🌐 First, create and move to your project directory:

sh
mkdir my-app
cd my-app

为项目创建必要的文件。创建一个名为 package.json 的文件,内容如下:

🌐 Create the necessary files for the project. Make a package.json file with the following:

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

同样,创建一个 tsconfig.json 文件,内容如下:

🌐 Similarly, create a tsconfig.json file with the following:

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

接下来,安装必要的模块。

🌐 Next, install the necessary 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. 你好,世界

🌐 2. Hello World

编辑 index.html

🌐 Edit 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 是用于注册服务工作者的脚本:

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 事件。这允许 Hono 应用拦截对 /sw 的访问。

🌐 In sw.ts, create an application using Hono and register it to the fetch event with the Service Worker adapter’s handle function. This allows the Hono application to intercept access to /sw.

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()

🌐 Using fire()

fire() 函数会自动为你调用 addEventListener('fetch', handle(app)),使代码更加简洁。

🌐 The fire() function automatically calls addEventListener('fetch', handle(app)) for you, making the code more concise.

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. 跑

🌐 3. Run

启动开发服务器。

🌐 Start the development server.

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

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

🌐 By default, the development server will run on port 5173. Access http://localhost:5173/ in your browser to complete the Service Worker registration. Then, access /sw to see the response from the Hono application.

Hono 中文网 - 粤ICP备13048890号