Created
January 18, 2015 02:02
-
-
Save bahmutov/730e33366acc4ca07003 to your computer and use it in GitHub Desktop.
Change downloaded javascript using ServiceWorker
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
/* | |
Using ServiceWorker, every request (except from iframes) can be intercepted and the javascript | |
could be changed before returning the result. Here is an example that if "*foo.js" is | |
requested, downloads it, but then returns 'console.log("hi there");' | |
Related: https://github.com/bahmutov/service-turtle/issues/7 | |
*/ | |
var allowJavaScriptFromAnywhere = { | |
'Access-Control-Allow-Origin': '*', | |
'Content-Type': 'text/javascript; charset=utf-8' | |
}; | |
function javascriptResponse(src) { | |
var responseOptions = { | |
status: 200, | |
headers: allowJavaScriptFromAnywhere | |
}; | |
return new Response(src, responseOptions); | |
} | |
self.addEventListener('fetch', function (event) { | |
// if page tries to download foo.js | |
if (/foo\.js$/.test(event.request.url)) { | |
event.respondWith( | |
fetch(event.request.clone()) | |
.then(function (response) { | |
// response has possible text / json / blob as promises | |
return response.text().then(function (src) { | |
// src - original source code | |
var transformedSource = 'console.log("hi there, from ServiceWorker!");'; | |
// construct new response with changed JavaScript source | |
return javascriptResponse(transformedSource); | |
}); | |
}) | |
); | |
return; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment