Changing the font family of the BBC News website using a cloudflare worker.
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 site = 'www.bbc.co.uk'; | |
const subdomain1 = 'm.files.bbci.co.uk'; | |
addEventListener('fetch', event => { | |
const request = event.request | |
event.respondWith(handleRequest(request)) | |
}); | |
async function handleRequest(request) { | |
const url = new URL(request.url); | |
if(url.pathname === "/robots.txt") { | |
return new Response('User-agent: *\nDisallow: /', {status: 200}); | |
} | |
const xhost = request.headers.get('x-host'); | |
if(!xhost) { | |
return new Response('x-host header missing', {status: 403}); | |
} | |
url.hostname = xhost; | |
const acceptHeader = request.headers.get('accept'); | |
if(xhost === site){ | |
if(acceptHeader && acceptHeader.indexOf('text/html') >= 0){ | |
let oldResponse = await fetch(url.toString(), request) | |
let newResponse = new HTMLRewriter() | |
/** | |
* Our modifications to the HTML go in here using the HTMLRewriter API | |
* https://developers.cloudflare.com/workers/runtime-apis/html-rewriter | |
*/ | |
.transform(oldResponse) | |
return newResponse | |
} | |
} | |
if(xhost === subdomain1){ | |
if(acceptHeader && acceptHeader.indexOf('text/css') >= 0){ | |
const response = await fetch(url.toString(), request); | |
let body = await response.text(); | |
body = body | |
.replace(/Arial,Helvetica,freesans,sans-serif/gi,'"Comic Sans MS", "Comic Sans", cursive;') | |
.replace(/Helvetica,Arial,freesans,sans-serif/gi,'"Comic Sans MS", "Comic Sans", cursive;'); | |
return new Response(body, { | |
headers: response.headers | |
}); | |
} | |
} | |
return await fetch(url.toString(), request); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment