Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed

- `HtmlRewriter` now inserts the head insert block only once, for the document's first `<head>`: pages embedding a nested HTML document or malformed markup with repeated `<head>` tags no longer run the inline script twice and throw a `SyntaxError` (#417)

## [5.6.0] - 2026-11-20

### Added
Expand Down
16 changes: 12 additions & 4 deletions src/zimscraperlib/rewriting/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,16 @@ def __init__(
self.pre_head_insert = pre_head_insert
self.post_head_insert = post_head_insert
self.notify_js_module = notify_js_module
self.head_insert_started = False
self.head_insert_done = False

def rewrite(self, content: str) -> RewritenHtml:
"""Rewrite HTML code passed"""
if self.output is not None:
raise Exception("ouput should not already be set") # pragma: no cover
self.output = io.StringIO()
self.head_insert_started = False
self.head_insert_done = False

self.base_href = extract_base_href(content)
self.css_rewriter = CssRewriter(self.url_rewriter, self.base_href)
Expand Down Expand Up @@ -270,14 +274,18 @@ def handle_starttag(self, tag: str, attrs: AttrsList, *, auto_close: bool = Fals
self.send(" />")
else:
self.send(">")
if tag == "head" and self.pre_head_insert:
self.send(self.pre_head_insert)
if tag == "head" and not self.head_insert_started:
self.head_insert_started = True
if self.pre_head_insert:
self.send(self.pre_head_insert)

def handle_endtag(self, tag: str):
"""Overwrite handle_endtag from HTMLParser"""
self.html_rewrite_context = None
if tag == "head" and self.post_head_insert:
self.send(self.post_head_insert)
if tag == "head" and self.head_insert_started and not self.head_insert_done:
self.head_insert_done = True
if self.post_head_insert:
self.send(self.post_head_insert)
self.send(f"</{tag}>")

def handle_startendtag(self, tag: str, attrs: AttrsList):
Expand Down
62 changes: 62 additions & 0 deletions tests/rewriting/test_html_rewriting.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,68 @@ def test_head_insert():
).replace("</head>", "POST_HEAD_INSERT</head>")


def test_head_insert_nested_document():
"""Head inserts must only be applied to the first <head> of the document.

Pages that embed a second, nested HTML document in their body (e.g. a CMS
storing a full page as data) must not get a duplicate insert, otherwise the
inline script runs twice and throws a SyntaxError.
"""
content = (
"<html><head><title>t</title></head><body>"
"<div><html><head></head><body>inner</body></html></div>"
"</body></html>"
)

url_rewriter = ArticleUrlRewriter(article_url=HttpUrl("http://kiwix.org/"))
result = (
HtmlRewriter(url_rewriter, "PRE_HEAD_INSERT", "POST_HEAD_INSERT", None)
.rewrite(content)
.content
)

assert result == (
"<html><head>PRE_HEAD_INSERT<title>t</title>POST_HEAD_INSERT</head><body>"
"<div><html><head></head><body>inner</body></html></div>"
"</body></html>"
)
assert result.count("PRE_HEAD_INSERT") == 1
assert result.count("POST_HEAD_INSERT") == 1


@pytest.mark.parametrize(
"content,expected",
[
(
"<html><head><head></head></head><body>x</body></html>",
(
"<html><head>PRE_HEAD_INSERT<head>POST_HEAD_INSERT</head></head>"
"<body>x</body></html>"
),
),
(
"<html><head></head><head></head><body>x</body></html>",
(
"<html><head>PRE_HEAD_INSERTPOST_HEAD_INSERT</head><head></head>"
"<body>x</body></html>"
),
),
("<html><body></head>x</body></html>", "<html><body></head>x</body></html>"),
],
)
def test_head_insert_malformed_head_tags(content: str, expected: str):
url_rewriter = ArticleUrlRewriter(article_url=HttpUrl("http://kiwix.org/"))
result = (
HtmlRewriter(url_rewriter, "PRE_HEAD_INSERT", "POST_HEAD_INSERT", None)
.rewrite(content)
.content
)

assert result == expected
assert result.count("PRE_HEAD_INSERT") <= 1
assert result.count("POST_HEAD_INSERT") <= 1


@pytest.mark.parametrize(
"js_src,expected_js_module_path",
[
Expand Down