How to check if service-worker exist in given URL?
You can look at Service Worker Detector, a Chrome extension that detects if a website registers a Service Worker by reading the navigator.serviceWorker.controller
property. It might also work in other browsers supporting Web Extensions, but it looks like it is not yet distributed as such.
However, it requires the script to be run in a browser, which might not cover your needs. You can try with a scriptable headless Chrome.
As suggested by Nicolas, this check can be done using headless Chrome.
Below is an example using Puppeteer:
'use strict'
const puppeteer = require('puppeteer');
(async() => {
try {
// Step 1: launch browser and open a new page.
const browser = await puppeteer.launch()
const page = await browser.newPage()
// Step 2: Go to a URL and wait for a service worker to register.
var url = 'https://web.dev/'
await page.goto(url)
const swTarget = await browser.waitForTarget(target => target.type() === 'service_worker')
// Step 3a: If a service worker is registered, print URL of SW file to the console
if(swTarget) {
console.log(swTarget._targetInfo['url'])
}
// Step 4: Done. Close.
await browser.close()
} catch (err) {
// The process will timeout after 30s, if no service worker is registered
console.error(err.message)
}
})()
If you want to do this in code, you can only do it within the same origin as the worker(s) you want to check for. Within the same origin, you can use getRegistration(url)
(which gives you a promise that will resolve to undefined
or a ServiceWorkerRegistration
object for the URL), or getRegistrations()
(which gives you a promise for an array of ServiceWorkerRegistration
objects). E.g.:
navigator.serviceWorker.getRegistrations().then(registrations => {
console.log(registrations);
});