Skip to content

Handle CDATA unintentionally treated as a conditional comment #1162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: gh-pages
Choose a base branch
from
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
11 changes: 11 additions & 0 deletions src/htmlparser.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,17 @@ function HTMLParser(html, handler) {
}
}

// Treat <![CDATA[...]]> as a comment for backward compatibility. It was
// was unintentionally parsed as a conditional comment before
// https://github.com/kangax/html-minifier/pull/1162.
if (html.startsWith('<![CDATA[')) {
var cdataEnd = html.indexOf(']]>');
handler.comment(html.substring(2, cdataEnd + 2), true /* non-standard */);
html = html.substring(cdataEnd + 3);
prevTag = '';
continue;
}

// https://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment
if (/^<!\[/.test(html)) {
var conditionalEnd = html.indexOf(']>');
Expand Down
20 changes: 20 additions & 0 deletions tests/minifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -623,6 +623,26 @@ QUnit.test('collapsing space in conditional comments', function(assert) {
}), output);
});

QUnit.test('treat CDATA as comments for backward compatibility', function(assert) {
var input;

input = '<![CDATA[line 1\nline 2]]>';
assert.equal(minify(input), input);
assert.equal(minify(input, { removeComments: true }), '');
input = '<p><![CDATA[line 1\nline 2]]></p>';
assert.equal(minify(input), input);
assert.equal(minify(input, { removeComments: true }), '<p></p>');

input = '<![CDATA[]]>';
assert.equal(minify(input), input);
assert.equal(minify(input, { removeComments: true }), '');

// https://github.com/kangax/html-minifier/issues/1161
input = '<![CDATA[___]><-___]]>';
assert.equal(minify(input), input);
assert.equal(minify(input, { removeComments: true }), '');
});

QUnit.test('remove comments from scripts', function(assert) {
var input, output;

Expand Down