How do I use service workers with an htaccess protected directory?

我与影子孤独终老i 提交于 2021-02-08 07:34:20

问题


I'm trying some basic service workers. The service worker itself will work normally the first time the service worker is registered. The problem I always get is once the person revisits the website in the future (e.g. the following day) and tries to access a .htaccess/.htpasswd protected directory. Instead of getting the dialog box, as normal, they go straight to a 401 error.

This is how I am registering the service worker in script tags in the HTML.

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

I have tried a couple of different methods in the sw.js itself and every time I get the same error. This is one from the Google airhorner example, I believe...

self.addEventListener('install', e => {
  const timeStamp = Date.now();
  e.waitUntil(
    caches.open('somename').then(cache => {
      return cache.addAll([
        `/`,
        `/index.html`,
        `/css/tour-2.css`
      ])
          .then(() => self.skipWaiting());
    })
  );
});

self.addEventListener('activate', event => {
      event.waitUntil(self.clients.claim());
});

self.addEventListener('fetch', event => {
  event.respondWith(
    caches.match(event.request, {ignoreSearch: true}).then(response => {
      return response || fetch(event.request);
    })
  );
});

Does anyone know if it is possible to use service workers with websites with .htaccess protected directories?

Thanks.


回答1:


One way to cure is:

self.addEventListener('fetch', event => {
    // Exclude admin panel.
    if (0 === event.request.url.indexOf("https://www.my-site.com/my-protected-area")) {
        return;
    }

It should help.

Source: TIV.NET



来源:https://stackoverflow.com/questions/49620727/how-do-i-use-service-workers-with-an-htaccess-protected-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!