Skip to content

Commit 81a21c4

Browse files
committed
Ensure HTML code is encoded for display in search
Fixes #4404
1 parent f00d8fd commit 81a21c4

File tree

2 files changed

+18
-5
lines changed

2 files changed

+18
-5
lines changed

src/core/html.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,15 @@ export function getDecodedAttribute(element: Element, attrib: string) {
3737
}
3838
}
3939

40+
const kTagBrackets: Record<string, string> = {
41+
"<": "&lt;",
42+
">": "&gt;",
43+
};
44+
4045
const kAttrReplacements: Record<string, string> = {
4146
'"': "&quot;",
4247
"'": "&#039;",
43-
"<": "&lt;",
44-
">": "&gt;",
48+
...kTagBrackets,
4549
"&": "&amp;",
4650
};
4751
export function encodeAttributeValue(value: unknown) {
@@ -56,6 +60,13 @@ export function encodeAttributeValue(value: unknown) {
5660
}
5761
}
5862

63+
export function encodeHtml(value: string) {
64+
Object.keys(kTagBrackets).forEach((key) => {
65+
value = value.replaceAll(key, kTagBrackets[key]);
66+
});
67+
return value;
68+
}
69+
5970
export function findParent(
6071
el: Element,
6172
match: (el: Element) => boolean,

src/project/types/website/website-search.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ import { kLanguageDefaults } from "../../../config/constants.ts";
5151
import { pathWithForwardSlashes } from "../../../core/path.ts";
5252
import { isHtmlFileOutput } from "../../../config/format.ts";
5353
import { projectIsBook } from "../../project-context.ts";
54+
import { encodeHtml } from "../../../core/html.ts";
5455

5556
// The main search key
5657
export const kSearch = "search";
@@ -290,7 +291,7 @@ export async function updateSearchIndex(
290291
href: href,
291292
title,
292293
section: "",
293-
text: pageText.join("\n"),
294+
text: encodeHtml(pageText.join("\n")),
294295
});
295296
}
296297

@@ -302,14 +303,15 @@ export async function updateSearchIndex(
302303
const hrefWithAnchor = `${href}#${section.id}`;
303304
const sectionText = section.textContent.trim();
304305
h2.remove();
306+
305307
if (sectionText) {
306308
// Don't index empty sections
307309
updateDoc({
308310
objectID: hrefWithAnchor,
309311
href: hrefWithAnchor,
310312
title,
311313
section: sectionTitle,
312-
text: sectionText,
314+
text: encodeHtml(sectionText),
313315
});
314316
}
315317
}
@@ -325,7 +327,7 @@ export async function updateSearchIndex(
325327
href,
326328
title,
327329
section: "",
328-
text: mainText,
330+
text: encodeHtml(mainText),
329331
});
330332
}
331333
}

0 commit comments

Comments
 (0)