sanitize-htmlのdisallowedTagsModeの'escape'と'recursiveEscape'の違い
#sanitize-html #JavaScript #HTML
知りたいこと
sanitizeHtml(dirty, { disallowedTagsMode: '...' })のdisallowedTagsMode: 'escape'とdisallowedTagsMode: 'recursiveEscape'の違い。
違い
以下が公式READMEでの説明。
If you set disallowedTagsMode to recursiveEscape, the disallowed tags are escaped rather than discarded, and the same treatment is applied to all subtags, whether otherwise allowed or not.
サニタイズしないリスト(ホワイトリスト)にあっても入れ子になっていればサニタイズするのが'recursiveEscape'で、入れ子もサニタイズしないのが'escape'。
つまりrecursiveEscapeは入れ子のタグならどうかサニタイズされるようになる。そのため自然に期待するのは'escape'でのサニタイズの挙動だと思う。
テストから
以下はテストからの引用。
allowedTags: [...]を明示的に指定してないため、デフォルトで<div>や<p>は残るような挙動になる。
最初のテストのrecursiveEscapeの方は子要素の<p>はサニタイズされている。
一方次のテストのescapeの方は<p>は<p>のままになっている。
code:js
it('should escape markup not whitelisted even within allowed markup', function() {
assert.equal(
sanitizeHtml('<div><wiggly>Hello<p>World</p><tiggly>JS</tiggly></wiggly></div>', { disallowedTagsMode: 'recursiveEscape' }),
'<div>&lt;wiggly&gt;Hello&lt;p&gt;World&lt;/p&gt;&lt;tiggly&gt;JS&lt;/tiggly&gt;&lt;/wiggly&gt;</div>'
);
});
it('should escape markup not whitelisted even within allowed markup, but not the allowed markup itself', function() {
assert.equal(
sanitizeHtml('<div><wiggly>Hello<p>World</p><tiggly>JS</tiggly></wiggly></div>', { disallowedTagsMode: 'escape' }),
'<div>&lt;wiggly&gt;Hello<p>World</p>&lt;tiggly&gt;JS&lt;/tiggly&gt;&lt;/wiggly&gt;</div>'
);
});