Rackover Rackover - 2 months ago 7
HTML Question

javascript from ajax doesn't get proper execution

Using Ajax, i've created a sort of console that allows me to execute some PHP functions dynamically.

It looks like this screenshot

The problem is that after a bunch of commands, the console becomes hard to read. So i've created a javascript function, named "wipe();", which clears the containing the console.

I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.

But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.

I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a function from another <script></script> block.

So why is it failing to do that ?

here is the php code :

echo '<script>wipe();</script>';


and here is the the first <script> block:

var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");

function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.send();
}

function wipe(){
span.innerHTML = '';
}

Answer

To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a tag inserted via innerHTML should not execute.

A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");

function send(data) {
  window.setInterval(function() {
        var elem = document.getElementById('screen');
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
        xmlhttp.onloadend = function() {
          span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
          evalJSFromHtml(span.innerHTML);
        }
        xmlhttp.send();
      }

      function wipe() {
        span.innerHTML = '';
      }
Comments