I'm currently coding a web application, and I'm trying to educate myself on the use of service workers, for reasons of efficiency and resource availability.
I've seen that it's possible to intercept most client-side requests, and that's exactly the functionality I'm looking for.
However, my application uses iframes and I can't manage to intercept the request made by the src attribute.
Here's a POC:
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="https://static.licdn.com/sc/h/3m4lyvbs6efg8pyhv7kupo6dh">
<title>Service Worker Example</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<img src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com" style="width:104px;height:142px;">
<iframe src="https://www.w3schools.com"></iframe>
<iframe src="/index.html"></iframe>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(registration => {
console.log('Service Worker registered with scope:', registration.scope);
})
.catch(error => {
console.error('Service Worker registration failed:', error);
});
}
</script>
</body>
</html>
sw.js
self.addEventListener('fetch', event => {
console.log('Service worker, event for:', event.request.url);
event.respondWith(fetch(event.request));
});
Results:
We can see that requests initiated by the script and img tags have been intercepted by the service worker.
However, only one of the two requests initiated by the iframe tag was intercepted (the one whose origin is equivalent to my web application).
My aim is not to load an iframe that violates the Content Security Policy directive, but only to intercept the request made by the src attribute.
Thank you in advance for your help. If the service workers are not suitable for this purpose, but there are other methods, I'm open to it.
