简体   繁体   English

Service Worker - 排除路径

[英]Service Worker - excluding path

Is there a possibility to exclude some paths in service worker?是否有可能排除服务工作者中的某些路径?

For example, I have my application: www.application.com and an admin panel www.application.com/superadmin例如,我有我的应用程序: www.application.com和一个管理面板www.application.com/superadmin

I want to disable SW in /superadmin/* path.我想在/superadmin/*路径中禁用 SW。

I saw that there is a scope option, but in my case, it's must be / https://developer.mozilla.org/en-US/docs/Web/Manifest/serviceworker我看到有一个scope选项,但就我而言,它必须是/ https://developer.mozilla.org/en-US/docs/Web/Manifest/serviceworker

Maybe you have any ideas or experience on how to solve this problem?也许您对如何解决这个问题有任何想法或经验?

在这种情况下无法完全禁用 serviceworker(尽管您始终可以让 serviceworker 忽略对子路径的获取请求)-尽管有一项建议可以在将来启用更细粒度的 serviceworker 范围: https:// github.com/wanderview/service-worker-scope-pattern-matching/blob/master/explainer.md

There is a way.有一种方法。 We can add an array list of items to exclude, and add a search into the fetch event listener.我们可以添加要排除的项目的数组列表,并将搜索添加到获取事件侦听器中。

Include and exclude method below for completeness.为了完整性,包含和排除下面的方法。

var offlineInclude = [
    '',                // index.html
    'site.css',
    'js/sitejs.js'
];

var offlineExclude = [
    '/bigimg.png',                 //exclude a file
    '/networkimages/smallimg.png', //exclude a file in a specific directory
    '/admin/'                      //exclude a directory
];

self.addEventListener("install", function(event) {
  console.log('WORKER: install event in progress.');
  event.waitUntil(
    caches
      .open(version + 'fundamentals')
      .then(function(cache) {
        return cache.addAll(offlineInclude);
      })
      .then(function() {
        console.log('WORKER: install completed');
      })
  );
});

self.addEventListener("fetch", function(event) {
  console.log('WORKER: fetch event in progress.');

  if (event.request.method !== 'GET') {
    console.log('WORKER: fetch event ignored.', event.request.method, event.request.url);
    return;
  }

  for (let i = 0; i < offlineExclude.length; i++)
  {
    if (event.request.url.indexOf(offlineExclude[i]) !== -1)
    {
      console.log('WORKER: fetch event ignored. URL in exclude list.', event.request.url);
      return false;
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM