Last active
November 30, 2018 14:08
-
-
Save lvonk/a397dd0b35d55df5ceb832ca5a6745bc to your computer and use it in GitHub Desktop.
Proxy all fetch request using a service worker to prevent unwanted urls
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
<html> | |
<head> | |
<script> | |
if ('serviceWorker' in navigator) { | |
window.addEventListener('load', function() { | |
console.log('[APP] registering ServiceWorker') | |
navigator.serviceWorker.register('/sw.js').then(function(registration) { | |
// Registration was successful | |
console.log('[APP] ServiceWorker registration successful with scope: ', registration.scope); | |
}, function(err) { | |
// registration failed :( | |
console.log('[APP] ServiceWorker registration failed: ', err); | |
}); | |
}); | |
} | |
</script> | |
</head> | |
<body> | |
<h1>Hi there</h1> | |
<img src="https://www.nasa.gov/sites/default/files/thumbnails/image/nasa-logo-web-rgb.png"/> | |
</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
const ALLOWED_DOMAINS = [ | |
'localhost', | |
'www.nasa.gov', // commenting this will prevent the img from being loaded | |
] | |
const log = message => console.log("[SERVICE WORKER]: " + message) | |
self.addEventListener('fetch', function(event) { | |
const request_url = new URL(event.request.url) | |
log(request_url) | |
if(!ALLOWED_DOMAINS.includes(request_url.hostname)) { | |
event.respondWith(new Response('', { | |
status: 403, | |
statusText: `This domain ${request_url.hostname} is not allowed`, | |
})) | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just wondering if ☝️ is bulletproof? Or can it still be deregistered or removed by loading a malicious script in
index.html
?