Đinh Carabus
Đinh Carabus

Reputation: 3496

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. 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:

<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?

Upvotes: 1

Views: 321

Answers (1)

Maxim Khanov
Maxim Khanov

Reputation: 434

When you pass the HTML data to the browser by setting Element.innerHTML, the browser must interpret/parse the HTML to render it. Even though it doesn't specifically render the onclick property, it must still resolve the encoding. 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.

Using a simple HTML encoder like https://opinionatedgeek.com/codecs/htmlencoder , you can re-encode the string and it should return "&lt;html&gt;".

Upvotes: 1

Related Questions