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
	}) 
}
9 Likes

Why when trying to do 2 html replace in the same async fuction it doesn’t work?

async function handleRequest(request) {
	const response = await fetch(request)
	var html = await response.text()

	// Simple replacement regex
	html = html.replace( /assets/g , 'https://domain.com/assets/')
  html = html.replace( /sytlesheets/g , 'https://domain.com/stylesheets/')


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

The asset one works, the stylesheets doesn’t…why?

You have a spelling error. It should be /stylesheets/g not /sytlesheets/g

1 Like