Home > Net >  Service Worker 'Hello World' example
Service Worker 'Hello World' example

Time:03-08

I am learning about Service workers, as I have a usecase to create a fetch listener, that will pass back an arbitrary binary response.

I have no idea where to start. The examples I have seen online talk about making a server request, caching in the service worker, and passing it back. What I really want to do is just pass back my own response, not make a query to the server and cache it!

What I am looking for, as a start is, say something that will once the service worker is active, given the user enters in the browser, (or uses fetch api to get the following url)

http://myapp/helloworld

will show 'Helloworld' in the browser. The service worker will be something like the following. But I have not a clue how make it work.

self.addEventListener('fetch', event => {
   // compare end of url with /helloworld
   // if match, respond with 'helloword', otherwise fetch the response from the server 
});

CodePudding user response:

This is just going to be a very brief, broad overview of how I would tackle the problem.

First, I would follow a guide like this:

https://css-tricks.com/add-a-service-worker-to-your-site/

// Listen for request events
self.addEventListener('fetch', function (event) {

  // Get the request
  let request = event.request;
  ...
}

Then you'll use this bit of code as a guideline for what you want to do:

event.respondWith(
  fetch(request).then(function (response) {
    return response;
  }).catch(function (error) {
    return caches.match(request).then(function (response) {
      return response;
    });
  })
);

With some modifications.

First, you'll want to check if it's a normal non-/helloworld type of request, and if it is, do something like this:

if (normalRequest) {
  event.respondWith(
  fetch(request).then(function (response) {
    return response;
  });
} else {
  ... TODO
}

And in the TODO section, you'll do your helloworld code - it's not clear to me what you want to do with that, so I can't really go into more detail. But this is the overall structure I would use.

  • Related