In the ServiceWorker JavaScript code itself (not the page code), I would like to know my own URL. Or at least the own host.
I need this, because I want different cache behavior for resources from my own server and resources from other servers.
In other words: event.request.url
is allways a URL with host and path (like .html
). I need to know, if this URL is from the same host as the ServiceWorker itself is from.
In the ServiceWorker JavaScript code itself (not the page code), I would like to know my own URL. Or at least the own host.
I need this, because I want different cache behavior for resources from my own server and resources from other servers.
In other words: event.request.url
is allways a URL with host and path (like https://example./index.html
). I need to know, if this URL is from the same host as the ServiceWorker itself is from.
1 Answer
Reset to default 17Inside of a service worker execution context, self
is set to the ServiceWorkerGlobalScope
, which inherits from WorkerGlobalScope
. There's a location
property on WorkerGlobalScope
that can give you the info you want.
You can put that into practice to solve your problem via a helper method like:
function isSameOrigin(urlString) {
const urlOrigin = (new URL(urlString)).origin;
return urlOrigin === self.location.origin;
}