Created
July 8, 2016 10:06
-
-
Save 1999/868a999af31a7d25dd2811ab824cbea0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 fs = require('fs'); | |
const http = require('http'); | |
const hostname = '127.0.0.1'; | |
const port = 3000; | |
const respondWithHTML = res => { | |
res.statusCode = 200; | |
res.setHeader('Content-Type', 'text/html'); | |
res.end(` | |
<html> | |
<head> | |
<title>Example firefox SW referer</title> | |
</head> | |
<body> | |
<a href="/one">Link 1</a> | |
<a href="/two">Link 2</a> | |
<a href="/three">Link 3</a> | |
<script type="text/javascript"> | |
if (navigator.serviceWorker) { | |
navigator.serviceWorker.register('/service-worker.js'); | |
} | |
</script> | |
</body> | |
</html> | |
`); | |
} | |
const respondWithSW = res => { | |
res.statusCode = 200; | |
res.setHeader('Content-Type', 'text/javascript'); | |
res.end(fs.readFileSync(`${__dirname}/service-worker.js`)); | |
} | |
const server = http.createServer((req, res) => { | |
console.log(`${req.method} ${req.url} (referrer: ${req.headers.referer})`); | |
if (req.url === '/service-worker.js') { | |
respondWithSW(res); | |
} else { | |
respondWithHTML(res); | |
} | |
}); | |
server.listen(port, hostname, () => { | |
console.log(`Server running at http://${hostname}:${port}/`); | |
}); |
This file contains hidden or 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
try { | |
self.addEventListener('fetch', evt => { | |
const isFetch = (evt.request.method === 'GET'); | |
const isNavigate = (evt.request.mode === 'navigate'); | |
evt.respondWith(fetch(evt.request)); | |
}); | |
} catch (ex) { | |
console.error(`SW eval error: ${ex.message}`); | |
console.log(ex.stack); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment