0

According to this thread Can scripts be inserted with innerHTML? injecting some javascript in innerHTML is not supposed to work.

So why it does work in that case :

<BR>
Below is the code injected with a div
</BR>
<div id="div_content">
</div>    

<script>
function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*@cc_on
@if (@_jscript_version >= 5)
    try {
    pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
    }
    catch (e){
        try {
        pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
        }
        catch (e2){
        pageRequest = false
        }
    }
@end
@*/

if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()

if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously 
pageRequest.send(null)
embedpage(pageRequest)
}
}

function embedpage(request){
//if viewing page offline or the document was successfully retrieved online (status code=2000)
if (window.location.href.indexOf("http")==-1 || request.status==200)
///document.write(request.responseText)
div_content.innerHTML = request.responseText;
}

HttpRequest("http://localhost/ajax/injecthtml/demo4/external.html") //include "external.html" onto current page
</script>

external.html

<img src="google.jpg" alt="" width="" height="" onclick="alert('Embedded Javascript within innerHTML works !!!')">
<br>
<img src="google.jpg" alt="" width="" height="" onclick="alert('Embedded Javascript within innerHTML works !!!')">
Community
  • 1
  • 1
user310291
  • 36,946
  • 82
  • 271
  • 487
  • Are you sure about it? See this [fiddle](https://jsfiddle.net/v610Lyv0/) – Mosh Feu Dec 24 '15 at 09:56
  • @MoshFeu yes I'm sure since I tested it and made a screenshot from the test. I use pure Javascript, not jquery and it works. – user310291 Dec 24 '15 at 16:47
  • @MoshFeu maybe yours does not work because you use relative url, it must be absolute url at least in chrome for security reason. – user310291 Dec 24 '15 at 16:48

1 Answers1

2

The Javascript is not being executed when you load the page. You're just loading <img> tags that have onclick attributes, and when you click on them the code in the attributes is executed. That's just ordinary HTML.

What doesn't get executed when you assign to .innerHTML is <script> tags.

Barmar
  • 741,623
  • 53
  • 500
  • 612