How to test service worker locally?

Asked

Viewed 273 times

0

In my attempt to understand the workings of Workers services I’m trying to implement the same in a basic application I’m serving locally, the problem is that the service worker fails to register, looking more closely at the documentation I realize that they need HTTPS which leads me to question is it possible to test a service worker locally or only on the server in production? Here are my scripts:

My app implemented with express.

# app.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.listen(8080, () => {
  console.log('Application running...');
});

My home page (and only) that I want to crochet.

# index.html

<!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue"></script>
</head>
<body>
  <div id="app">
    <img src="https://vuejs.org/images/logo.png" alt="Vue logo">
    <h1>{{ greeting }}</h1>
    <ul>
      <li>
        To learn more about Vue, visit
        <a :href="docsURL" target="_blank">
          {{ humanizeURL(docsURL) }}
        </a>
      </li>
      <li>
        For live help with simple questions, check out
        <a :href="discordURL" target="_blank">
          the Discord chat
        </a>
      </li>
      <li>
        For more complex questions, post to
        <a :href="forumURL" target="_blank">
          the forum
        </a>
      </li>
    </ul>
  </div>

  <script>
    var app = new Vue({
      el: '#app',
      data: {
        greeting: 'Welcome to your Vue.js app!',
        docsURL: 'http://vuejs.org/guide/',
        discordURL: 'https://chat.vuejs.org',
        forumURL: 'http://forum.vuejs.org/'
      },
      methods: {
        humanizeURL: function (url) {
          return url
            .replace(/^https?:\/\//, '')
            .replace(/\/$/, '')
        }
      }
    })
  </script>
  <script charset="utf-8">
      if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/basic-pwa/sw.js')
        .then(function(reg) {

          if(reg.installing) {
            console.log('Service worker installing');
          } else if(reg.waiting) {
            console.log('Service worker installed');
          } else if(reg.active) {
            console.log('Service worker active');
          }
        }).catch(function(error) {
          // registration failed
          console.log('Registration failed with ' + error);
        });
      }
  </script>
</body>
</html>

My file referring to the service worker.

# sw.js

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('v1').then(cache => {
      return cache.addAll([
        '/basic-pwa/',
        '/basic-pwa/index.html'
      ]);
    });
  );
});


self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(resp) {
      return resp || fetch(event.request).then(function(response) {
        caches.open('v1').then(function(cache) {
          cache.put(event.request, response.clone());
        });
        return response;
      });
    }).catch(function() {
      return caches.match('');
    })
  );
});
  • The one where you saw that the SW needs to have HTTPS?

  • The documentation says that you can use Workers services on the developing localhost, but as you can see I’m not getting it to work.

1 answer

2


Service worker needs a safe environment, and "localhost" at door 80 is considered a safe environment.

If you need to perform a test in an unsafe environment, you can turn on a Chrome flag: Insecure origins treated as secure and register the url.

chrome://flags/#unsafely-treat-insecure-origin-as-secure

Obs.: remember that there is no point just caching the index.html. You need to cache any linked file besides the images including favicon.ico...

In your examples above, there is an error in Ws.js, follow file without error...

self.addEventListener(
  'install', 
  event => {
    event.waitUntil(
      caches.open('v1')
      .then(
        cache => {
          return cache.addAll(
            [
              '/',
              '/index.html'
            ]
          )
        }
      )
    );
  }
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.