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> 
2
  • 2
    stackoverflow.com/questions/2592092/… Commented Nov 29, 2016 at 13:52
  • Your usage of XMLHttpRequest#onreadystatechange is doomed to failure - you need to learn how to use XMLHttpRequest Commented Nov 29, 2016 at 14:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ahhh, good old regex on HTML - I hear Tony's hooves
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Ό

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.