0

I want to execute javascript from downloaded html file. I use XMLHttpRequest to get the html response.

function load2element() {

    localStorage.setItem("geadele", "cool variable is passed");

    var client = new XMLHttpRequest();
    client.open('GET', '/geadele/geadele/gesurvey.html');
    client.onreadystatechange = function() {
        el.innerHTML = client.responseText; // << file with javascript 
    }

    client.send();
}

imported gesurvey.html contains javascript codes for execution:

<script>
    console.log("From gesurvey.html");
    console.log(localStorage.getItem("geadele")); // should "cool variable is passed"
</script>

<div>I am survey</div>
Saurav Rastogi
  • 9,575
  • 3
  • 29
  • 41
Edgaras Karka
  • 7,400
  • 15
  • 61
  • 115

1 Answers1

0
function load2element() {
  localStorage.setItem("geadele", "cool variable is passed");
  var client = new XMLHttpRequest();
  client.open('GET', '/geadele/geadele/gesurvey.html');
  client.onreadystatechange = function() {
    var regex = /<script\b[^>]*>([\s\S]*?)<\/script>/g;
    var scriptContent = regex.exec(client.responseText);
    if (scriptContent.length) {
        var scriptTbExecuted = '"use strict"; ' + scriptContent[1];
        eval(scriptTbExecuted);
    }
  }
  client.send();
}

However, execution of eval is dangerous. strict mode eliminates some harmful behaviours, but you need to read about eval in strict mode considering the what you want to and content of that script.

erdysson
  • 1,450
  • 13
  • 17
  • ahhh, good old regex on HTML - I hear [Tony's hooves](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Jaromanda X Nov 29 '16 at 14:43
  • you can do the above without resorting to eval, AND allow multiple script tags AND even allow script tags with src attribute AND without summoning ZA̡͊͠͝LGΌ – Jaromanda X Nov 29 '16 at 14:46