@@ -220,7 +220,7 @@ const htmlEntities = {
220220}
221221
222222export function encodeHtml ( str ) {
223- if ( ! str ) return ''
223+ if ( typeof str !== 'string' || ! str ) return ''
224224 return str . replace ( / [ & < > " ' ] / g, m => htmlEntities [ m ] ) ;
225225}
226226
@@ -242,6 +242,52 @@ function htmlFormatClasses(type, tag, depth, cls, index) {
242242 return cls
243243}
244244
245+ const dangerousTags = [
246+ 'script' ,
247+ 'iframe' ,
248+ 'object' ,
249+ 'embed' ,
250+ 'link' ,
251+ 'style' ,
252+ 'meta' ,
253+ 'base' ,
254+ 'frame' ,
255+ 'frameset' ,
256+ 'applet' ,
257+ 'noscript' ,
258+ 'template'
259+ ]
260+ const anyDangerousTag = new RegExp ( `<(${ dangerousTags . join ( '|' ) } )` , 'i' )
261+
262+ export function sanitizeHtml ( html ) {
263+ if ( ! html || typeof html !== 'string' ) return html
264+
265+ let result = html
266+ let lowerResult = result . toLowerCase ( )
267+ function updateResult ( r ) {
268+ result = r
269+ lowerResult = result . toLowerCase ( )
270+ }
271+
272+ if ( anyDangerousTag . test ( lowerResult ) ) {
273+ for ( const tag of dangerousTags ) {
274+ const tagOpen = `<${ tag } `
275+
276+ if ( lowerResult . indexOf ( tagOpen ) === - 1 ) continue
277+
278+ const regex = new RegExp ( `<${ tag } [^>]*>([\\s\\S]*?)<\\/${ tag } >` , 'gi' )
279+ updateResult ( result . replace ( regex , '' ) )
280+
281+ if ( lowerResult . indexOf ( tagOpen ) !== - 1 ) {
282+ const selfClosingRegex = new RegExp ( `<${ tag } [^>]*\\/?>` , 'gi' )
283+ updateResult ( result . replace ( selfClosingRegex , '' ) )
284+ }
285+ }
286+ }
287+
288+ return result
289+ }
290+
245291/**
246292 * Returns an ever-increasing unique integer id.
247293 */
@@ -280,6 +326,7 @@ export function utilsFunctions() {
280326 isHtml,
281327 htmlFormatClasses,
282328 encodeHtml,
329+ sanitizeHtml,
283330 hashString,
284331 }
285332}
0 commit comments