服务工作者“Hello World”例子
我正在学习服务工作者,因为我有一个用例来创建一个获取侦听器,它将传回任意二进制响应。
我不知道从哪里开始。我在网上看到的示例讨论了发出服务器请求、在 Service Worker 中缓存并将其传回。我真正想做的只是传回我自己的响应,而不是向服务器查询并缓存它!
我正在寻找的,首先是,一旦服务工作者处于活动状态,用户在浏览器中输入(或使用 fetch api 获取以下网址)
http://myapp/helloworld
将显示浏览器中的“Helloworld”。 Service Worker 将类似于以下内容。但我不知道如何让它发挥作用。
self.addEventListener('fetch', event => {
// compare end of url with /helloworld
// if match, respond with 'helloword', otherwise fetch the response from the server
});
I am learning about Service workers, as I have a usecase to create a fetch listener, that will pass back an arbitrary binary response.
I have no idea where to start. The examples I have seen online talk about making a server request, caching in the service worker, and passing it back. What I really want to do is just pass back my own response, not make a query to the server and cache it!
What I am looking for, as a start is, say something that will once the service worker is active, given the user enters in the browser, (or uses fetch api to get the following url)
http://myapp/helloworld
will show 'Helloworld' in the browser. The service worker will be something like the following. But I have not a clue how make it work.
self.addEventListener('fetch', event => {
// compare end of url with /helloworld
// if match, respond with 'helloword', otherwise fetch the response from the server
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这只是我将如何解决这个问题的一个非常简短、广泛的概述。
首先,我会遵循这样的指南:
https:// /css-tricks.com/add-a-service-worker-to-your-site/
然后,您将使用这段代码作为您想要执行的操作的指南:
进行一些修改。
首先,您需要检查它是否是正常的非 /helloworld 类型的请求,如果是,请执行以下操作:
在 TODO 部分中,您将执行您的
helloworld
代码- 我不清楚你想用它做什么,所以我无法详细说明。但这是我将使用的整体结构。This is just going to be a very brief, broad overview of how I would tackle the problem.
First, I would follow a guide like this:
https://css-tricks.com/add-a-service-worker-to-your-site/
Then you'll use this bit of code as a guideline for what you want to do:
With some modifications.
First, you'll want to check if it's a normal non-/helloworld type of request, and if it is, do something like this:
And in the TODO section, you'll do your
helloworld
code - it's not clear to me what you want to do with that, so I can't really go into more detail. But this is the overall structure I would use.