简体   繁体   中英

Inject HTML with Cloudflare worker

I'm trying to use HTMLRewriter to inject a preload <link> into web pages on my site, but nothing is happening.

The code I am using is:

addEventListener("fetch", (event) => {
  event.respondWith(
    handleRequest(event.request).catch(
      (err) => new Response(err.stack, { status: 500 })
    )
  );
});

class ElementHandler {
  element(element) {
    element.append(`<link rel="preload" href="path/to/image.jpg" as="image">`, {html: true});
  }
}

async function handleRequest(req) {
  const res = await fetch(req)
  return new HTMLRewriter().on("head", new ElementHandler()).transform(res)
}

I spoke to somebody from Cloudflare and they couldn't see anything wrong with it, but it's still not working. The <link > isn't there.

Ensure the route you are hitting is setup in your routes section. The routes section can be found under your domain > Workers > Add Route

I wish I could post an image but here is a guide I wrote using your code snippet for injecting a style into an application called FoundryVTT: https://dev.to/mbround18/how-to-hijack-your-head-38dn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM