Service Worker html 响应未显示在浏览器上

Service Worker html Response not been displayed on the browser

我正在尝试使用 html 回复来响应服务工作者事件,但我没有在浏览器上获得任何输出。我不明白 why.Here 是我的代码。

self.addEventListener('fetch', function(event) {

event.respondWith
{
    new Response("<h1>Hello!</h1>", {
    headers: {'Content-Type': 'text/html'}
})};    
});

Respondwith 是一个函数。应该用括号 func(params) 中的参数调用,像这样

event.respondWith( new Response("<h1>Hello!</h1>", {
    headers: {'Content-Type': 'text/html'}
}))

有很多原因导致这不起作用

  • 不在 HTTPS、localhost 或 127.0.0.1 环境中
  • service worker 文件地址不对

如果你使用 Chrome 你可以使用 chrome://inspect/#service-workers 检查你的 service worker