Is there any way for a ServiceWorker to identify the source or origin of a no-cors/opaque FetchEvent.Request
? Or can we explicitly pass identifying information/data from the HTML to the ServiceWorker
that could be used to identify origins of FetchEvents
?. I hacked together a solution using query string parameters, but I'm looking for something more native or elegant than this:
HTML
<img id="img1" src="image.jpg?imgId=img1" />
<img id="img2" src="image.jpg?imgId=img2" />
Service Worker
self.addEventListener('fetch', event => {
const url = new URL(event.request.url);
if(url.pathname.endsWith('/image.jpg')) {
// get Element ID that initated the FetchEvent
const imgId = url.searchParams.get('imgId');
// Notify document that the fetch started
clients.get(event.clientId)
.then(client => client.postMessage({imgId}));
}
})