Exos
Exos

Reputation: 3988

Insert JavaScript code from JavaScript

i need gets a html code by jsonp like method, and display this on a div element. This works with simple html like an images, text, etc. But now the code can content a JavaScript tags and need insert this on a div, but the javascript, don't runs, i resume it with a example:

var div = document.getElementById('mydiv');

div.innerHTML = '<scipt type="text/javascript"> console.log('I run!'); </script>';

this don't works, too i probe:

var otherdiv = document.createElement('div');

otherdiv.innerHTML = '<scipt type="text/javascript"> console.log('I run!'); </script>';

div.appendChild(otherdiv);

But don't works too.

How I can insert the code in away that the JavaScript runs?

Upvotes: 1

Views: 239

Answers (2)

Halcyon
Halcyon

Reputation: 57709

The most straightforward way is to extract all JavaScript and eval it.

You can extract JavaScript with a regular expressions like:

var match = html.match(new RegExp("<script[^>]*>(.+)</script>"));
console.log(match);

This is a far from optimal way of executing JavaScript, very error prone and possibly unsafe. I would strongly advise against it.

Upvotes: 1

BishopZ
BishopZ

Reputation: 6378

You should use a script loader like LAB, yep/nope, or Frame.js. The browser has built-in restrictions, script loading is the best practice for including scripts on a page.

You also would have to escape the single quotes.

console.log(\'I run!\');

Upvotes: 0

Related Questions