Skip to content

Query Parameters on the registration URL #587

@develohpanda

Description

@develohpanda

Hi! Thank you for this wonderful plugin.

I'm working on something that would greatly benefit from being able to pass query parameters to the service worker registration URL. Something like, /sw.js?version=1.0.3. This way, within an incoming service worker I am able to do new URL(self.location).searchParams.get('version'), and pass information to an incoming service worker during updates. (See SO answer)

Example

One example of a use case would be that by sending a query parameter, I am able to convey to an incoming service worker information about the currently running application/service worker. Then, I can check whether the incoming service worker should force-install (via self.skipWaiting() and claim and refresh all clients in the activate event). I will be able to compare the version of the incoming service worker (let's say 2.0.0) with the current application (1.0.3 from the query parameter).

This is useful because it allows the incoming service worker to determine independently it's installation behavior, and we don't need to rely on currently running code (from the assets served by the existing service worker) to do the force update. This is fairly critical to my use case and I'm exploring what options are available.

// sw.js

const version = `2.0.1`;

const url = new URL(self.location);
const currentVersion = url.searchParams.get('version');
	
const shouldAutoActivate = // check whether currentVersion -> version is a minor or major upgrade

self.addEventListener('install', () => {
	if (shouldAutoActivate) {
		self.skipWaiting();
	}
});

self.addEventListener('activate', () => {
	if (shouldAutoActivate) {
		return self.clients.matchAll()
		    .then(function(clients) {
				clients.forEach(client => client.navigate(client.url))
		    });
	}
});

Alternative

Is there a way to send query parameters currently, that I am missing? I am using React, and there is not a way to use the useRegisterSW() utility hook to send query parameters, nor a way to set additional query parameters in the VitePWAOptions.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions