Last active
April 8, 2016 12:42
-
-
Save hsablonniere/ec8cf9229974a5cf431715999c6da58b to your computer and use it in GitHub Desktop.
SW intercept JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"foo": "bar", | |
"baz": [ | |
{ "id": 1, "name": "one" }, | |
{ "id": 2, "name": "two" }, | |
{ "id": 3, "name": "three" }, | |
{ "id": 4, "name": "four" } | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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