Skip to main content
Home

Built and signed on GitHub Actions

Provides missing HTMRewriter for platforms that do not have it, besides Cloudflare Workers and Bun.

This package works with Node.js, DenoIt is unknown whether this package works with Cloudflare Workers, Bun
It is unknown whether this package works with Cloudflare Workers
This package works with Node.js
This package works with Deno
It is unknown whether this package works with Bun
JSR Score
76%
Published
11 months ago (0.2.0)

HTMLRewriter

Provides the same HTMLRewriter for all platforms.

Examples

Rewrite URL links in HTML:

import { HTMLRewriter } from "@sntran/html-rewriter";

export default {
  async fetch(request) {
    const OLD_URL = "developer.mozilla.org";
    const NEW_URL = "mynewdomain.com";

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

    const rewriter = new HTMLRewriter()
      .on("a", new AttributeRewriter("href"))
      .on("img", new AttributeRewriter("src"));

    const res = await fetch(request);
    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;
    }
  },
};
Built and signed on
GitHub Actions

New Ticket: Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@sntran/html-rewriter

Import symbol

import * as html_rewriter from "@sntran/html-rewriter";
or

Import directly with a jsr specifier

import * as html_rewriter from "jsr:@sntran/html-rewriter";

Add Package

pnpm i jsr:@sntran/html-rewriter
or (using pnpm 10.8 or older)
pnpm dlx jsr add @sntran/html-rewriter

Import symbol

import * as html_rewriter from "@sntran/html-rewriter";

Add Package

yarn add jsr:@sntran/html-rewriter
or (using Yarn 4.8 or older)
yarn dlx jsr add @sntran/html-rewriter

Import symbol

import * as html_rewriter from "@sntran/html-rewriter";

Add Package

npx jsr add @sntran/html-rewriter

Import symbol

import * as html_rewriter from "@sntran/html-rewriter";

Add Package

bunx jsr add @sntran/html-rewriter

Import symbol

import * as html_rewriter from "@sntran/html-rewriter";