Simple Response
Once the SW is in control, it can hijack requests to servers and respond with anything you want. You can send a simple “Hello world” string.
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('Hello world')
);
});
Through the Network panel you’ll find the content type of the response, set by default to text/plain
.
So if you try to send HTML code such as Hello <b>world</b>
it will be displayed in the document as is, as plain text.
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('Hello <b>world</b>', {
headers: {'foo': 'bar'}
})
);
});
Custom Response
Modify Response Header
Fortunately, We can set headers
as part of the response.
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('Hello world', {
headers: {'foo': 'bar'}
})
);
});
Save it. Refresh the Network panel, and you’ll see the Headers
updated with the new values.
Remember to check the Force update on page load checkbox on your SW in the Sources panel.
Respond with Markup
self.addEventListener('fetch', function(event) {
event.respondWith(
new Response('<h1 class="a-winner-is-me">Hello world!</h1>' , {
headers: {'Content-Type':'text/html'}
})
);
});
We’ve managed to create something that works entirely offline-first.
Now if you bring the server down, it still works!