Skip to content

Instantly share code, notes, and snippets.

@Nooshu
Created March 11, 2021 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nooshu/d45a48e8f5aa6ed758889c7953fee286 to your computer and use it in GitHub Desktop.
Save Nooshu/d45a48e8f5aa6ed758889c7953fee286 to your computer and use it in GitHub Desktop.
Changing the font family of the BBC News website using a cloudflare worker.
// what are the domains we are wanting to modify
const site = 'www.bbc.co.uk';
const subdomain1 = 'm.files.bbci.co.uk';
// do this on a fetch
addEventListener('fetch', event => {
const request = event.request
event.respondWith(handleRequest(request))
});
async function handleRequest(request) {
// store the URL
const url = new URL(request.url);
// disallow crawlers (write a robots.txt file)
if(url.pathname === "/robots.txt") {
return new Response('User-agent: *\nDisallow: /', {status: 200});
}
// when overrideHost is used in a WPT script, WPT sets x-host to original host i.e. site we want to proxy
// store the value of x-host
const xhost = request.headers.get('x-host');
// If the `x-host` header is missing, abort and tell us
if(!xhost) {
return new Response('x-host header missing', {status: 403});
}
// set our hostname to that listed in the x-host header
url.hostname = xhost;
// get the accept header to allow us to examine the type of request it is
const acceptHeader = request.headers.get('accept');
// check if the resource is being served from the main site domain
if(xhost === site){
// check for an accept header and what it contains
if(acceptHeader && acceptHeader.indexOf('text/html') >= 0){
// store this particular HTML response for modification
let oldResponse = await fetch(url.toString(), request)
// create a new response
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 the modified page
return newResponse
}
}
// check if the resource is being served from subdomain 1
if(xhost === subdomain1){
// Change CSS here
if(acceptHeader && acceptHeader.indexOf('text/css') >= 0){
// grab the CSS response
const response = await fetch(url.toString(), request);
// extract the body of the request
let body = await response.text();
// swap out our font family in the CSS body
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 the modified response
return new Response(body, {
headers: response.headers
});
}
}
// add additional domains here
// otherwise just proxy the request unmodified
return await fetch(url.toString(), request);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment