Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle fetch in service worker but allow client to see redirect

I have a url, /users/sign_out, that is supposed log out a user and redirect them to my root url, /. I want to handle this fetch through my service worker, because I want to clean some items out of the cache before sending the user back to root. However, since the client doesn't see the redirect that happens on the fetch from the service worker, the user winds up on my splash screen but sees the pre-redirect address /users/sign_out.

Is there any way currently that I can handle the fetch and also allow the client to see the correct final url?

It appears that eventually there will be a Response.redirect() method that will allow updating a response with the final url. It looks like there is also likely to be some kind of finalURL option that would also address this case. But is there anything that I can use now? On Twitter, Jake Archibald (@jaffathecake) said I could construct a new Response myself - and I can, but even after looking at the spec and the MDN docs a bit, I still can't figure out how to specify the correct url for it.

If there is in fact a way to construct a Response object that does what I need, could someone show me how that works?

like image 841
Brendan Ritchie Avatar asked Jul 02 '15 20:07

Brendan Ritchie


1 Answers

There's an example at https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/mock-responses showing how you could create a Response object and use it to respond to a fetch event.

In that case, we're creating a 200 OK response with a body, but there's nothing stopping you from creating an arbitrary response. You'd probably want a 302 Found for your use case, so you'd do something like:

var responseInit = {
  status: 302,
  statusText: 'Found',
  headers: {
    Location: '/' // Or whatever URL you want to redirect to.
  }
};

var redirectResponse = new Response('', responseInit);
event.respondWith(redirectResponse);

You can include code that clears your caches inside the fetch handler before you respond to the event, and you'd obviously want to check the event.request.url value first to make sure you only respond to requests for /users/sign_out with your custom response.

like image 183
Jeff Posnick Avatar answered Oct 06 '22 01:10

Jeff Posnick