Cloudflare Workers Search and Replace Image

Hello everyone,

I am trying to search and replace an image with Cloudflare workers. I figured out that I propably have to use the HTMLRewriter, however so far I did not manage to get it working at all. Maybe someone in the Cloudflare Community got an idea. :slight_smile:

So here is what I want to replace (somwhere in my HTML):
<img src="software/html5/imgs/topmenu/test1.ico" alt="Test1">

And I want to replace it with e.g.:
<img src="https://cdn4.iconfinder.com/data/icons/32x32-free-design-icons/32/Info.png" alt="Test1">

However when alt=“Test2” I do not want to replace anything. I only want to replace it when alt=“Test3”.

Thank you all very much!

Rick

Here’s what I’ve got so far. Unfortunatelly it does not work… And also I don’t know how I can do it only to the img tags where the alt=“Test1”…

async function handleRequest(req) {
  const res = await fetch(req)
  return rewriter.transform(res)
}
 
 class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName
  }
 
  element(element) {
    const attribute = element.getAttribute(this.attributeName)
    if (attribute) {
      element.setAttribute(
        this.attributeName,
        attribute.replace('software/html5/imgs/topmenu/test1.ico', 'https://cdn4.iconfinder.com/data/icons/32x32-free-design-icons/32/Info.png')
      )
    }
  }
}

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

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

Rick