File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -254,23 +254,25 @@ function sanitizeHtml(
254254 element . setAttribute ( 'target' , '_blank' ) ;
255255 }
256256 } else {
257- element . insertAdjacentHTML ( 'afterend' , element . innerHTML ) ;
257+ // Disallowed tag: mark, and unwrap only after traversal
258258 toRemove . push ( element ) ;
259259 }
260260 }
261261
262- for ( const element of toRemove ) {
263- try {
264- try {
265- element . parentNode ?. removeChild ( element ) ;
266- } catch {
267- element . outerHTML = '' ;
268- }
269- } catch {
270- try {
271- element . remove ( ) ;
272- } catch { }
262+ // Unwrap disallowed elements by moving their child nodes before them
263+ // and then dropping the now-empty element.
264+ // Iterate in reverse to start from the innermost elements
265+ // and limit the size of the trees we move.
266+ for ( let i = toRemove . length - 1 ; i >= 0 ; i -- ) {
267+ const element = toRemove [ i ] ;
268+ const parent = element . parentNode ;
269+ if ( ! parent ) continue ; // already removed
270+ // copy each of its children above it
271+ while ( element . firstChild ) {
272+ parent . insertBefore ( element . firstChild , element ) ;
273273 }
274+ // then remove it
275+ parent . removeChild ( element ) ;
274276 }
275277
276278 const styleList = doc . querySelectorAll ( 'style' ) ;
You can’t perform that action at this time.
0 commit comments