Worker script to rewrite body HTML

Hi,
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
{
	constructor(attributeName)
	{
		this.attributeName = attributeName;
	}

	element(element)
	{
		const attribute = element.getAttribute(this.attributeName);
		if (attribute) element.setAttribute(this.attributeName, attribute.replace('myolddomain.com', 'mynewdomain.com'));
	}
}

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 => {
	event.respondWith(handleRequest(event.request));
})

@fallon @jpugh

3 Likes

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!

Could you show me an example?

Please check out https://www.w3schools.com/jsref/jsref_replace.asp. 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.

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