HTMLRewritingStream

Classin html-rewriter@fastly/js-compute 4.0.0since 3.35.0View source

Implements TransformStream.

Lets you rewrite HTML by registering callbacks on CSS selectors. When an element matching the selector is encountered, the rewriter calls your callback, which can manipulate the element's attributes and add or remove content from the immediate context.

HTMLRewritingStream implements TransformStream, so you can pipe an HTML response body through it using pipeThrough.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { HTMLRewritingStream } from 'fastly:html-rewriter';
async function handleRequest(event) {
let transformer = new HTMLRewritingStream()
.onElement("h1", e => e.prepend("Header: "))
.onElement("div", e => e.setAttribute("special-attribute", "top-secret"));
let body = (await fetch("https://example.com/")).body.pipeThrough(transformer);
return new Response(body, {
status: 200,
headers: new Headers({
"content-type": "text/html; charset=utf-8",
})
});
}
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));

Constructor

new HTMLRewritingStream()

Properties

The writable stream to which HTML content should be written.

The readable stream from which transformed HTML content can be read.

Methods

onElement

View source
onElement(selector: string, handler: (element: Element) => void): this

Registers a callback for elements matching the given CSS selector. The callback is called once for each matching element. Elements added by handlers will not be processed by other handlers.

Supported CSS selectors:

Pattern Description
* Any element
E All elements of type E
E F F elements inside E elements
E > F F elements directly inside E elements
E:nth-child(n) The n-th child of type E
E:first-child First child of type E
E:nth-of-type(n) The n-th sibling of type E
E:first-of-type First sibling of type E
E:not(s) Type E elements not matching selector s
E.myclass Type E elements with class "myclass"
E#myid Type E elements with ID "myid"
E[attr] Type E elements with attribute attr
E[attr="val"] Type E elements where attr is "val"
E[attr="val" i] Case-insensitive match
E[attr="val" s] Case-sensitive match
E[attr~="val"] attr contains "val" in a space-separated list
E[attr|="val"] attr is hyphen-separated and starts with "val"
E[attr^="val"] attr starts with "val"
E[attr$="val"] attr ends with "val"
E[attr*="val"] attr contains "val"

Parameters

selector: string

CSS selector string

handler: (element: Element) => void

Function called with each matching Element

Returns

this

The HTMLRewritingStream instance for chaining

Throws

  • Error If the provided selector is not a valid CSS selector or if the handler is not a function.