Skip to content

Instantly share code, notes, and snippets.

@hsablonniere
Last active April 8, 2016 12:42
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 hsablonniere/ec8cf9229974a5cf431715999c6da58b to your computer and use it in GitHub Desktop.
Save hsablonniere/ec8cf9229974a5cf431715999c6da58b to your computer and use it in GitHub Desktop.
SW intercept JSON
{
"foo": "bar",
"baz": [
{ "id": 1, "name": "one" },
{ "id": 2, "name": "two" },
{ "id": 3, "name": "three" },
{ "id": 4, "name": "four" }
]
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SW intercept JSON</title>
</head>
<body>
<pre></pre>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw.js')
.then(function () {
console.log('sw registered');
fetchDataAndPutInPre();
})
.catch(function () {
console.log('sw : something went wrong');
});
}
else {
fetchDataAndPutInPre();
}
function fetchDataAndPutInPre() {
fetch('./data.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
document.querySelector('pre').innerHTML = JSON.stringify(data, null, ' ');
})
.catch(function () {
console.log('fetch : something went wrong');
});
}
</script>
</body>
</html>
'use strict';
self.addEventListener('fetch', function (event) {
if (event.request.url.match(/\.json$/)) {
event.respondWith(
fetch(event.request)
.then(function (response) {
return response.json();
})
.then(function (data) {
data.baz = data.baz.map(function (item) {
return item.name;
});
return new Response(JSON.stringify(data), {
headers: {
'Content-Type': 'application/json',
}
});
})
.catch(function (err) {
console.log(err, 'c la merde');
})
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment