Worker script to rewrite body HTML

I’m looking for a worker script that rewrite’s URLs in the response body.
I found a few example scripts, but none workers will accept.

I wonder if somebody can help me with the script found here titled " Rewrite URLs"

I am currently seeing an error when attempting to use the script
"Uncaught ReferenceError: Cannot access 'AttributeRewriter' before initialization at line 7"

Seems to be an issue with the example. The class is used before it is defined (greetings from C :smile:)

Try the following

class AttributeRewriter
		this.attributeName = attributeName;

		const attribute = element.getAttribute(this.attributeName);
		if (attribute) element.setAttribute(this.attributeName, attribute.replace('', ''));

const rewriter = new HTMLRewriter()
	.on('a', new AttributeRewriter('href'))
	.on('img', new AttributeRewriter('src'));

async function handleRequest(req)
	const res = await fetch(req);
	return rewriter.transform(res);

addEventListener('fetch', event => {

@fallon @jpugh


awesome, thank you so much

what if I wanted to rewrite more than 1 domain, any chance you could help me out with that?

Concatenating another replace() call to .replace() should do the trick.

Thanks all, we’re updating this in the docs today. Appreciate the initial bug report @jackpea!

Please check out Thats a very fundamental JavaScript question and you’ll need to understand what it is doing before copy/pasting anything. You basically need to call replace on replace.

1 Like

Thanks for pointing that out @jackpea and helping troubleshoot @sandro!