Antimony Antimony - 1 month ago 17
Javascript Question

How to parse URLs in a Service Worker

I am trying to write a Service Worker to cache part of my webpage, but I need the origin and path of each request in order to decide how to handle it. Unfortunately, the Request object only has the full URL as a string, and I can't find any way to parse it.

URL parsing is a complicated and error prone process so I'd prefer to use native functionality if possible, but the only method I can find to parse URLs in Javascript involves abusing the DOM

<a>
element, which is obviously not an option in the service worker context. What should I do?

Answer

You can use the URL API for that.
It gives you the ability to create a new URL object from a string and use the components:

var a = new URL('http://www.domain.com/asdf/?a=b#123');
console.log(a)

a.searchParams.forEach(function(val, key){
  console.log(key + ' ' + val);
});

It's an experimental API, but its available in Web Workers, so it should be good.