Skip to content

Instantly share code, notes, and snippets.

@lvonk
Last active November 30, 2018 14:08
Show Gist options
  • Save lvonk/a397dd0b35d55df5ceb832ca5a6745bc to your computer and use it in GitHub Desktop.
Save lvonk/a397dd0b35d55df5ceb832ca5a6745bc to your computer and use it in GitHub Desktop.
Proxy all fetch request using a service worker to prevent unwanted urls
<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>
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`,
}))
}
});
@lvonk
Copy link
Author

lvonk commented Nov 30, 2018

Just wondering if ☝️ is bulletproof? Or can it still be deregistered or removed by loading a malicious script in index.html?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment