Skip to content

Commit aa2ae5a

Browse files
authored
fix(sanitize-html): emit transformTags text on empty tags when textFilter is set (#5494)
When a transformTags handler adds text to an allowed tag that originally had no text content, the injected text was silently dropped if any textFilter was configured. The onopentag branch that emits frame.innerText was guarded by !options.textFilter, deferring emission to ontext so the filter could run there. For an empty element htmlparser2 never fires ontext, so the text was emitted by neither branch. Emit frame.innerText through options.textFilter here when present (mirroring the discard path), so the transformTags text contract holds for empty tags regardless of whether a textFilter is set.
1 parent 6e9d3fc commit aa2ae5a

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

‎packages/sanitize-html/index.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -540,8 +540,13 @@ function sanitizeHtml(html, options, _recursing) {
540540
result += ' />';
541541
} else {
542542
result += '>';
543-
if (frame.innerText && !hasText && !options.textFilter) {
544-
result += escapeHtml(frame.innerText);
543+
if (frame.innerText && !hasText) {
544+
const escaped = escapeHtml(frame.innerText);
545+
if (options.textFilter) {
546+
result += options.textFilter(escaped, name);
547+
} else {
548+
result += escaped;
549+
}
545550
addedText = true;
546551
}
547552
}

‎packages/sanitize-html/test/test.js‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,24 @@ describe('sanitizeHtml', function() {
323323
}), '<a href="http://somelink">some new text</a>');
324324
});
325325

326+
it('should add new text to an empty tag when transforming function sets it and an identity textFilter is present', function () {
327+
assert.equal(sanitizeHtml('<a></a>', {
328+
allowedTags: [ 'a' ],
329+
textFilter: function (text) {
330+
return text;
331+
},
332+
transformTags: {
333+
a: function (tagName, attribs) {
334+
return {
335+
tagName,
336+
attribs,
337+
text: 'some new text'
338+
};
339+
}
340+
}
341+
}), '<a>some new text</a>');
342+
});
343+
326344
it('should preserve text when initially set and replace attributes when they are changed by transforming function', function () {
327345
assert.equal(sanitizeHtml('<a href="http://somelink">some initial text</a>', {
328346
transformTags: {

0 commit comments

Comments
 (0)