Skip to content

Instantly share code, notes, and snippets.

@jeffposnick
Created February 7, 2018 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffposnick/da9782fd96514b8fdf5e07a64580d431 to your computer and use it in GitHub Desktop.
Save jeffposnick/da9782fd96514b8fdf5e07a64580d431 to your computer and use it in GitHub Desktop.
<html>
<head>
<title>Test</title>
</head>
<body>
<p>
Open the DevTools console and take a look at the log messages when clicking the buttons below. Try taking your browser offline and try again.
</p>
<p>
The service worker is able to send messages to the client page to distinguish between the image load failue due to an invalid URL and due to a network failure.
</p>
<div>
<button data-img="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png">
Add a Valid Opaque Image URL
</button>
<button data-img="https://www.google.com/does-not-exist.png">
Add an Invalid Opaque Image URL
</button>
</div>
<script>
const channel = new BroadcastChannel('sw-info');
channel.addEventListener('message', (event) => {
console.log(`The request for ${event.data.url} resulted in ${event.data.status}`);
});
navigator.serviceWorker.register('sw.js');
navigator.serviceWorker.ready.then(() => {
for (const button of document.querySelectorAll('button')) {
button.addEventListener('click', () => {
const img = document.createElement('img');
img.src = button.dataset.img;
document.body.appendChild(img);
});
}
});
</script>
</body>
</html>
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', () => self.clients.claim());
const channel = new BroadcastChannel('sw-info');
self.addEventListener('fetch', (event) => {
if (event.request.url.endsWith('.png')) {
event.respondWith(
fetch(event.request)
.then((response) => {
channel.postMessage({status: response.status, url: event.request.url});
return response;
})
.catch((error) => {
channel.postMessage({status: error.message, url: event.request.url});
return Response.error();
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment