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