How to access the CF Object in HtmlRewriter?

I want to send some location info from the CF Object back to the browser in the HTML. The CF Object is available from the request.

async function handleRequest(request) {
  response = await fetch(request);
  return rewriter.transform(response);
}

const rewriter = new HTMLRewriter()
  .on('body', new AttributeWriter())

class AttributeWriter {
  async element(element) {
  // ...
  }
}

It looks like I’ll need to instantiate a new HtmlRewriter on every request and pass in the CF Object via the constructor.

Has anyone seen an actual API for HtmlRewriter? I.e., maybe there’s a way to pass more info via .transform(). I’d like to know the function’s signature. But I’ve only found the manually-written doc page.

Constructing a new HTMLRewriter on every request is very cheap. You can store your class AttributeWriter externally though, and then pass things into that as you need them. For example:

async function handleRequest(request) {
  const response = await fetch(request);
  const rewriter = new HTMLRewriter()
    .on('body', new AttributeWriter(request));
  return rewriter.transform(response);
}

class AttributeWriter {
  constructor(request) {
    this.foo = request.cf.bar;
  }
  async element(element) {
    // use this.foo
    // ...
  }
}

For completeness, the full HTMLRewriter typings can be found at workers-types/htmlrewriter.d.ts at 771ce7591e63bf47f36b39d60afb86e1fe8d404b · cloudflare/workers-types · GitHub