Search code examples
javascriptcloudflare-workers

Setting attribute using HTMLRewriter on Cloudflare worker


I am trying to set the value attribute of my #email field via a Cloudflare worker.

I define my email as [email protected] but how can I send this into ElementHandler ?

At the moment I am able to set the value attribute to be XXXX and this works successfully.

async function handleRequest(request) {

  const newResponse = new Response(response.body, response)

  const email = '[email protected]';

  return new HTMLRewriter()
     .on("#email", new ElementHandler())
     .transform(newResponse)

}

class ElementHandler {
   element(e) {
     e.setAttribute('value', 'XXXX')
   }
}

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

Solution

  • You can give your ElementHandler class a constructor that accepts parameters which you store in properties of the object:

    class ElementHandler {
      constructor(value) {
        this.value = value;
      }
    
      element(e) {
        e.setAttribute('value', this.value)
      }
    }
    

    Then construct it like:

    new ElementHandler(email)