简体   繁体   English

innerHTML是否自动转义HTML字符串的一部分?

[英]innerHTML auto-unescapes parts of HTML string?

I have to inject a string of html code containing inline event handlers into an element using innerHTML. 我必须使用innerHTML将包含嵌入式事件处理程序的html代码字符串注入到元素中。 Something like this: 像这样:

document.getElementById('some-div')
  .innerHTML = '<button onclick="alert(\'&lt;html&gt;\');">&lt;html&gt;</button>';

I expected to get this result: 我期望得到以下结果:

<button onclick="alert('&lt;html&gt;');">&lt;html&gt;</button>';

but the actual DOM looks like this: 但是实际的DOM看起来像这样:

<button onclick="alert('<html>');">&lt;html&gt;</button>';

Why is the inline event handler part automatically unescaped by the browser? 为什么内联事件处理程序部分会被浏览器自动取消转义? Can this be prevented without double-escaping? 如果没有两次转义,是否可以防止这种情况发生?

When you pass the HTML data to the browser by setting Element.innerHTML, the browser must interpret/parse the HTML to render it. 通过设置Element.innerHTML将HTML数据传递给浏览器时,浏览器必须解释/解析HTML才能呈现它。 Even though it doesn't specifically render the onclick property, it must still resolve the encoding. 即使它没有专门呈现onclick属性,它仍必须解析编码。 As Chris Barr said, you have to re-encode the string so that when the browser parses it, it will parse into the correct version. 正如克里斯·巴尔(Chris Barr)所说,您必须重新编码字符串,以便浏览器解析该字符串时,它将解析为正确的版本。

Using a simple HTML encoder like https://opinionatedgeek.com/codecs/htmlencoder , you can re-encode the string and it should return "&lt;html&gt;". 使用简单的HTML编码器(例如https://opinionatedgeek.com/codecs/htmlencoder) ,您可以重新编码字符串,并且该字符串应返回“&lt; html&gt;”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM