javascript - 使用 Service Worker 时离线重写 URL

标签 javascript node.js .htaccess mod-rewrite service-worker

我正在使用由名为 sw-precache 的 Nodejs 插件生成的服务工作线程来制作具有离线功能的 Web 应用程序。 。一切正常,我可以离线访问 html 文件或图像。

但是,由于您没有可能的服务器端语言,有没有办法像 .htaccess 文件一样在客户端重写 url?就像当没有文件与 url 匹配时显示“404 页面未找到”页面一样?我知道可以使用 Javascript 或元标记进行重定向,但是重写 url 吗?

最佳答案

默认情况下,当请求的 URL 是它已缓存的资源的 URL 时,sw-precache 将仅响应 fetch 事件。如果有人导航到不存在网页的 URL,则 sw-precache 将不会响应 fetch 事件。

这确实意味着您有机会在附加的 fetch 事件处理程序中运行自己的代码,该事件处理程序可以实现自定义行为,例如在以下情况下返回 404.html 页面:用户在离线状态下导航到不存在的页面。您需要跨越几个障碍,但具体操作方法如下:

// In custom-offline-import.js:
self.addEventListener('fetch', event => {
  if (event.request.mode === 'navigate') {
    event.respondWith(
      fetch(event.request)
        .catch(() => caches.match('404.html', {ignoreSearch: true}))
        // {ignoreSearch: true} is needed, since sw-precache appends a search
        // parameter with versioning information.
    );
  }
});

// In your sw-precache config:
{
  // Make sure 404.html is picked up in one of the glob patterns:
  staticFileGlobs: ['404.html'],
  // See https://github.com/GoogleChrome/sw-precache#importscripts-arraystring
  importScripts: ['custom-offline-import.js'],
}

这不应干扰 sw-precache 正在执行的任何操作,因为它将仅用作后备。

关于javascript - 使用 Service Worker 时离线重写 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42491242/

相关文章:

javascript - 条件渲染表行 React

javascript - Styled-component 没有注入(inject)所有不同的 css 来处理不同的 Prop

javascript - 分配给变量的基本 node.js 回调

node.js - 带有自定义回调的 Passport 本地策略永远不会起作用

php - 子目录中的 Zend 应用程序使 Zend 布局链接正常工作

asp.net - IE 8 上页面方法调用的 Json 问题

javascript - 如何在单击 jQuery 时将 +200 毫秒添加到 css 动画持续时间

javascript - Node Js中TCP连接中套接字的.on函数是什么

apache - apache htaccess 中的 mod_expires

php - htaccess URL 重写最大参数长度