Skip to content

Instantly share code, notes, and snippets.

@Nooshu
Created March 15, 2021 09:14
Show Gist options
  • Save Nooshu/a546aaba23b6f64eb4812d39387c87c1 to your computer and use it in GitHub Desktop.
Save Nooshu/a546aaba23b6f64eb4812d39387c87c1 to your computer and use it in GitHub Desktop.
Changing the font family of the BBC News website using a cloudflare worker.
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