0

I'm making an AJAX request to retrieve some JavaScript wrapped in <script>-tags that should be inserted on the current page. How can I make the inserted code execute upon insertion?

I'm using this snippet to append the code:

function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}

The HTML retrieved (responseText) looks something like this:

<script>
    console.log('Injected!');
</script>

So how can I make the <script> tags execute?

Script_Coded
  • 709
  • 8
  • 21

1 Answers1

0

Assuming that you receive some markup with scipt tags here and there you cannot eval something as the other question suggests.

jQuery is your ready to use option, assuming you are willing to use it.

$('#output').html('<p>Hello, Foo.</p><scr' + 'ipt>alert(\'foo\')</scr' + 'ipt>');

will execute the script and add markup. Notice how script tags in my code are augmented. This is important so the browser does not mistake the closing script tag in javascript string literal with the real closing tag of the script that is being executed. But if you load markup from server it is not an issue.

Also using this method it is advised to load markup only from a trusted resource because scripts will run.

P.S. if you don't plan on using jQuery (if you can't for some reason) you may want to check out their implementation and use it alone. (I mean check out their source code) but only if you are up to it.

Olga
  • 1,648
  • 1
  • 22
  • 31
  • Thank you! That could definitely work. But if I want to get the script from my php, could I then echo that code Into a hidden element and copy it from that element with jQuery? – Script_Coded Jul 29 '15 at 11:21