This worker modifies the response HTML.
Last active
July 24, 2020 05:04
-
-
Save rstacruz/6e252457754506e949619ddb17a9ca4b to your computer and use it in GitHub Desktop.
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
addEventListener('fetch', event => { | |
let response = handleRequest(event.request) | |
event.respondWith(response) | |
}) | |
async function handleRequest(request) { | |
const url = new URL(request.url) | |
// Proxy devhints.io => my-other-website.netlify.app | |
// and inject some markup | |
if (url.host === 'devhints.io') { | |
url.host = 'my-other-website.netlify.app' | |
let res = await fetch(url.toString(), request) | |
res = await injectMarkup(request, res) | |
return res | |
} | |
} | |
async function injectMarkup(req, res) { | |
if (!res.ok) return res | |
// Only process text/html responses | |
const type = res.headers.get('content-type') | |
if (!type.match(/^text\/html/)) return res | |
// Update the body text | |
const body = await res.text() | |
const ip = request.headers.get('cf-connecting-ip') | |
const html = body.replace( | |
'<html ', | |
`<html data-connecting-ip="${ip}" ` | |
) | |
return new Response(html, res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment