Reputation: 3496
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(\'<html>\');"><html></button>';
I expected to get this result:
<button onclick="alert('<html>');"><html></button>';
but the actual DOM looks like this:
<button onclick="alert('<html>');"><html></button>';
Why is the inline event handler part automatically unescaped by the browser? Can this be prevented without double-escaping?
Upvotes: 1
Views: 321
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 "<html>".
Upvotes: 1