Perform regex replacements and inject CSS/JavaScript with Cloudflare Workers

I was surprised there’s no recipe for this, so I wrote the snippet below:

addEventListener('fetch', event => {
	event.passThroughOnException()
	event.respondWith(handleRequest(event.request))
})

/**
 * Fetch and log a given request object
 * @param {Request} request
 */
async function handleRequest(request) {
	const response = await fetch(request)
	var html = await response.text()

	// Simple replacement regex
	html = html.replace( /Source Phrase/g , 'Target Phrase')

	// Inject scripts
	const customScripts = '<style type="text/css">body{background:red}</style></body>'
	html = html.replace( /<\/body>/ , customScripts)

	// return modified response
	return new Response(html, {
		headers: response.headers
	}) 
}
2 Likes