HTML rewrite via Worker Service not working

Hi,

I’m trying to automatically rewrite a SEO tag (canonical) within the HTML on every page of my website ontopit.com.au. The measures of success are:

  1. For https://ontopit.com.au/
    automated rewrite <link rel="canonical" href="https://www.ontopit.com.au/">
    to <link rel="canonical" href="https://ontopit.com.au/">

  2. For https://ontopit.com.au/partner-visa
    automated rewrite <link rel="canonical" href="https://www.ontopit.com.au/partner-visa">
    to <link rel="canonical" href="https://ontopit.com.au/partner-visa">

I’ve deployed a Worker Service called canonical-tag-rewriter with a .ontopit.com.au/ route at least 15 days ago, but it is not automatically rewriting the line of HTML on any pages. This is my first attempt to implement HTML rewrite. I’m on a paid subscription and paid workers plan. I’ve exhausted all online documentation. Any assistance appreciated - thanks.

Worker settings:

Worker Triggers > Custom Domain = ontopit.com.au
Worker Triggers > Route = *.ontopit.com.au/*
All other settings are default.

Worker Javascript deployed:

// start
const OLD_URL = 'www.ontopit.com.au';
const NEW_URL = 'ontopit.com.au';

async function handleRequest(req) {
  const res = await fetch(req);
  const contentType = res.headers.get('Content-Type');

  // If the response is HTML, it can be transformed with
  // HTMLRewriter -- otherwise, it should pass through
  if (contentType.startsWith('text/html')) {
    return rewriter.transform(res);
  } else {
    return res;
  }

}

class AttributeRewriter {
  constructor(attributeName) {
    this.attributeName = attributeName;
  }
  element(element) {
    const attribute = element.getAttribute(this.attributeName);
    if (attribute) {
      element.setAttribute(this.attributeName, attribute.replace(/replace.OLD_URL/g, NEW_URL));
    }
  }

}

const rewriter = new HTMLRewriter()
  .on('link', new AttributeRewriter('href'));

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

});

// end

Compare this line from your worker

With the one from the Rewrite links · Cloudflare Workers docs example

element.setAttribute(this.attributeName, attribute.replace(OLD_URL, NEW_URL));

Hi - thanks for your suggestion. That is how I originally had my code. I’ve reverted it, and now works in combination with changing:

    const attribute = element.getAttribute(this.attributeName);

to:

    var attribute = element.getAttribute(this.attributeName);

Turns out Javascript will not throw an error if you execute replace() on a constant. Instead it returns the original value.

I cut and paste the erroneous "const attribute " code from the example on Cloudflares /introducing-htmlrewriter/ page. I’ll let Cloudflare know that example has the bug.

Thanks
Gary

I have used this, exactly as the demo code I linked to shows, without issue.