Bun

HTMLRewriter

HTMLRewriter 允许您使用 CSS 选择器来转换 HTML 文档。它适用于 RequestResponse 以及 string。Bun 的实现基于 Cloudflare 的 lol-html

用法

一个常见的用例是重写 HTML 内容中的 URL。以下示例会将图像源和链接 URL 重写为使用 CDN 域

// Replace all images with a rickroll
const rewriter = new HTMLRewriter().on("img", {
  element(img) {
    // Famous rickroll video thumbnail
    img.setAttribute(
      "src",
      "https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg",
    );

    // Wrap the image in a link to the video
    img.before(
      '<a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">',
      { html: true },
    );
    img.after("</a>", { html: true });

    // Add some fun alt text
    img.setAttribute("alt", "Definitely not a rickroll");
  },
});

// An example HTML document
const html = `
<html>
<body>
  <img src="/cat.jpg">
  <img src="dog.png">
  <img src="https://example.com/bird.webp">
</body>
</html>
`;

const result = rewriter.transform(html);
console.log(result);

这将用 Rick Astley 的缩略图替换所有图像,并将每个 <img> 包装在一个链接中,产生如下差异

<html>
  <body>
     <img src="/cat.jpg">
     <img src="dog.png">
     <img src="https://example.com/bird.webp">
     <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">
       <img src="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" alt="Definitely not a rickroll">
     </a>
     <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">
       <img src="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" alt="Definitely not a rickroll">
     </a>
     <a href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">
       <img src="https://img.youtube.com/vi/dQw4w9WgXcQ/maxresdefault.jpg" alt="Definitely not a rickroll">
     </a>
  </body>
</html>

现在页面上的所有图像都将被替换为 Rick Astley 的缩略图,点击任何图像都会导向 一个非常著名的视频

输入类型

HTMLRewriter 可以转换各种来源的 HTML。输入会根据其类型自动处理

// From Response
rewriter.transform(new Response("<div>content</div>"));

// From string
rewriter.transform("<div>content</div>");

// From ArrayBuffer
rewriter.transform(new TextEncoder().encode("<div>content</div>").buffer);

// From Blob
rewriter.transform(new Blob(["<div>content</div>"]));

// From File
rewriter.transform(Bun.file("index.html"));

请注意,Cloudflare Workers 的 HTMLRewriter 实现仅支持 Response 对象。

元素处理器

on(selector, handlers) 方法允许您为匹配 CSS 选择器的 HTML 元素注册处理器。在解析过程中,处理器会针对每个匹配的元素调用

rewriter.on("div.content", {
  // Handle elements
  element(element) {
    element.setAttribute("class", "new-content");
    element.append("<p>New content</p>", { html: true });
  },
  // Handle text nodes
  text(text) {
    text.replace("new text");
  },
  // Handle comments
  comments(comment) {
    comment.remove();
  },
});

处理器可以是异步的,并返回一个 Promise。请注意,异步操作会阻塞转换,直到它们完成

rewriter.on("div", {
  async element(element) {
    await Bun.sleep(1000);
    element.setInnerContent("<span>replace</span>", { html: true });
  },
});

CSS 选择器支持

on() 方法支持各种 CSS 选择器

// Tag selectors
rewriter.on("p", handler);

// Class selectors
rewriter.on("p.red", handler);

// ID selectors
rewriter.on("h1#header", handler);

// Attribute selectors
rewriter.on("p[data-test]", handler); // Has attribute
rewriter.on('p[data-test="one"]', handler); // Exact match
rewriter.on('p[data-test="one" i]', handler); // Case-insensitive
rewriter.on('p[data-test="one" s]', handler); // Case-sensitive
rewriter.on('p[data-test~="two"]', handler); // Word match
rewriter.on('p[data-test^="a"]', handler); // Starts with
rewriter.on('p[data-test$="1"]', handler); // Ends with
rewriter.on('p[data-test*="b"]', handler); // Contains
rewriter.on('p[data-test|="a"]', handler); // Dash-separated

// Combinators
rewriter.on("div span", handler); // Descendant
rewriter.on("div > span", handler); // Direct child

// Pseudo-classes
rewriter.on("p:nth-child(2)", handler);
rewriter.on("p:first-child", handler);
rewriter.on("p:nth-of-type(2)", handler);
rewriter.on("p:first-of-type", handler);
rewriter.on("p:not(:first-child)", handler);

// Universal selector
rewriter.on("*", handler);

元素操作

元素提供了多种操作方法。所有修改方法都返回元素实例以便链式调用

rewriter.on("div", {
  element(el) {
    // Attributes
    el.setAttribute("class", "new-class").setAttribute("data-id", "123");

    const classAttr = el.getAttribute("class"); // "new-class"
    const hasId = el.hasAttribute("id"); // boolean
    el.removeAttribute("class");

    // Content manipulation
    el.setInnerContent("New content"); // Escapes HTML by default
    el.setInnerContent("<p>HTML content</p>", { html: true }); // Parses HTML
    el.setInnerContent(""); // Clear content

    // Position manipulation
    el.before("Content before")
      .after("Content after")
      .prepend("First child")
      .append("Last child");

    // HTML content insertion
    el.before("<span>before</span>", { html: true })
      .after("<span>after</span>", { html: true })
      .prepend("<span>first</span>", { html: true })
      .append("<span>last</span>", { html: true });

    // Removal
    el.remove(); // Remove element and contents
    el.removeAndKeepContent(); // Remove only the element tags

    // Properties
    console.log(el.tagName); // Lowercase tag name
    console.log(el.namespaceURI); // Element's namespace URI
    console.log(el.selfClosing); // Whether element is self-closing (e.g. <div />)
    console.log(el.canHaveContent); // Whether element can contain content (false for void elements like <br>)
    console.log(el.removed); // Whether element was removed

    // Attributes iteration
    for (const [name, value] of el.attributes) {
      console.log(name, value);
    }

    // End tag handling
    el.onEndTag(endTag => {
      endTag.before("Before end tag");
      endTag.after("After end tag");
      endTag.remove(); // Remove the end tag
      console.log(endTag.name); // Tag name in lowercase
    });
  },
});

文本操作

文本处理器提供文本操作方法。文本块代表文本内容的一部分,并提供有关它们在文本节点中位置的信息

rewriter.on("p", {
  text(text) {
    // Content
    console.log(text.text); // Text content
    console.log(text.lastInTextNode); // Whether this is the last chunk
    console.log(text.removed); // Whether text was removed

    // Manipulation
    text.before("Before text").after("After text").replace("New text").remove();

    // HTML content insertion
    text
      .before("<span>before</span>", { html: true })
      .after("<span>after</span>", { html: true })
      .replace("<span>replace</span>", { html: true });
  },
});

注释操作

注释处理器允许对注释进行操作,其方法与文本节点类似

rewriter.on("*", {
  comments(comment) {
    // Content
    console.log(comment.text); // Comment text
    comment.text = "New comment text"; // Set comment text
    console.log(comment.removed); // Whether comment was removed

    // Manipulation
    comment
      .before("Before comment")
      .after("After comment")
      .replace("New comment")
      .remove();

    // HTML content insertion
    comment
      .before("<span>before</span>", { html: true })
      .after("<span>after</span>", { html: true })
      .replace("<span>replace</span>", { html: true });
  },
});

文档处理器

onDocument(handlers) 方法允许您处理文档级别的事件。这些处理器会在文档级别发生的事件(而非特定元素内的事件)被调用

rewriter.onDocument({
  // Handle doctype
  doctype(doctype) {
    console.log(doctype.name); // "html"
    console.log(doctype.publicId); // public identifier if present
    console.log(doctype.systemId); // system identifier if present
  },
  // Handle text nodes
  text(text) {
    console.log(text.text);
  },
  // Handle comments
  comments(comment) {
    console.log(comment.text);
  },
  // Handle document end
  end(end) {
    end.append("<!-- Footer -->", { html: true });
  },
});

响应处理

转换 Response 时

  • 状态码、标头和其他响应属性会得到保留
  • 正文在保持流式传输能力的同时被转换
  • 内容编码(如 gzip)会自动处理
  • 转换后,原始响应正文会被标记为已使用
  • 标头会被克隆到新响应中

错误处理

HTMLRewriter 操作在多种情况下可能会抛出错误

  • on() 方法中的选择器语法无效
  • 转换方法中的 HTML 内容无效
  • 处理 Response 正文时的流错误
  • 内存分配失败
  • 输入类型无效(例如,传递 Symbol)
  • 正文已使用错误

应捕获并适当地处理错误

try {
  const result = rewriter.transform(input);
  // Process result
} catch (error) {
  console.error("HTMLRewriter error:", error);
}

参见

您还可以阅读 Cloudflare 文档,该 API 旨在与其兼容。