コンテンツにスキップ

リンクの書き換え

HTMLRewriterを使用してHTML内のURLリンクを書き換えます。これはJAMstackウェブサイトに便利です。

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");
// レスポンスがHTMLの場合、HTMLRewriterで変換できます
// それ以外の場合はそのまま通過させるべきです
if (contentType.startsWith("text/html")) {
return rewriter.transform(res);
} else {
return res;
}
},
};