This is possible only if you register the service worker first, for example the user has opened somehow your app page that registers a service-worker.
Consider the following simple page:
index.html
<!DOCTYPE html>
<html lang="en">
<body>
Sample App
<script src="app.js"></script>
</body>
</html>
Below the content of app.js
if ('serviceWorker' in navigator){
navigator.serviceWorker
.register('./service-worker.js')
.then(function (registration) {
console.log("Service Worker Registered");
})
.catch(function (err) {
console.log("Service Worker Failed to Register", err)
})
}
And finally our service-worker.js file below
//Ran when SW is installed.
self.addEventListener('install', function (event) {
console.log("[ServiceWorker] Installed");
});
//Service Worker Activate
self.addEventListener('activate', function(event) {
console.log("[ServiceWorker] Activating");
});
//Fetch Events
self.addEventListener('fetch', function(event) {
var requestUrl = new URL(event.request.url);
var keyParam = requestUrl.searchParams.get("key");
if (requestUrl.origin === location.origin && event.request.url.includes('/confirmation')) {
event.respondWith(
//do something else
new Response("ok this key is already used " + keyParam, { "status" : 200 , "statusText" : "MyOwnResponseHaha!" })
)
}
})
So to conclude first of all your user must open somehow the index.html file to successfully install and register the service worker. Once this is done, any request(from a link in an email or directly in the browser address bar) that will be directed to let's say
http://yourdomain.com/confirmation?key=1234567
will be intercepted by service-worker.js and instead the following result will be returned:
"ok this key is already used 1234567"
OBS: However there are so many problems that can go wrong with that, that I do not recommend pursuing this course of action. Like for example, how do you check if key is already used? or if the user opened index.html in Chrome, then the service worker will be registered in Chrome. If for example Edge is the computer's default browser, then when he will click on the email link, an Edge instance will open, and the Edge browser will not have a service worker installed so the above link will return 404... Try to find another way. but it is trully amazing how SW can be used as an app router.