Antimony Antimony - 1 year ago 105
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

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

Answer Source

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('');

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download