Skip to content

Commit

Permalink
[search] filter script and style elements from search result summary …
Browse files Browse the repository at this point in the history
…text. (#12057)

Co-authored-by: Bénédikt Tran <[email protected]>
  • Loading branch information
jayaddison and picnixz authored Mar 17, 2024
1 parent b2069fb commit bf0bec3
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 15 deletions.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ Bugs fixed
Patch by Bénédikt Tran.
* #11894: Do not add checksums to css files if building using the htmlhelp builder.
Patch by mkay.
* #12052: Remove ``<script>`` and ``<style>`` tags from the content of search result
summary snippets.
Patch by James Addison.

Testing
-------
Expand Down
4 changes: 3 additions & 1 deletion sphinx/themes/basic/static/searchtools.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,9 @@ const Search = {

htmlToText: (htmlString, anchor) => {
const htmlElement = new DOMParser().parseFromString(htmlString, 'text/html');
htmlElement.querySelectorAll(".headerlink").forEach((el) => { el.remove() });
for (const removalQuery of [".headerlinks", "script", "style"]) {
htmlElement.querySelectorAll(removalQuery).forEach((el) => { el.remove() });
}
if (anchor) {
const anchorContent = htmlElement.querySelector(`[role="main"] ${anchor}`);
if (anchorContent) return anchorContent.textContent;
Expand Down
41 changes: 27 additions & 14 deletions tests/js/searchtools.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,33 @@ describe('Basic html theme search', function() {
describe("htmlToText", function() {

const testHTML = `<html>
<div class="body" role="main">
<section id="getting-started">
<h1>Getting Started</h1>
<p>Some text</p>
</section>
<section id="other-section">
<h1>Other Section</h1>
<p>Other text</p>
</section>
<section id="yet-another-section">
<h1>Yet Another Section</h1>
<p>More text</p>
</section>
</div>
<body>
<script src="directory/filename.js"></script>
<div class="body" role="main">
<script>
console.log('dynamic');
</script>
<style>
div.body p.centered {
text-align: center;
margin-top: 25px;
}
</style>
<!-- main content -->
<section id="getting-started">
<h1>Getting Started</h1>
<p>Some text</p>
</section>
<section id="other-section">
<h1>Other Section</h1>
<p>Other text</p>
</section>
<section id="yet-another-section">
<h1>Yet Another Section</h1>
<p>More text</p>
</section>
</div>
</body>
</html>`;

it("basic case", () => {
Expand Down

0 comments on commit bf0bec3

Please sign in to comment.