1

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?

4
  • It should be <script>, not <scipt> (missing an R), and it'll have to be inserted into the live dom, not just dangling in nowhereland. Commented Apr 27, 2012 at 18:40
  • in your second snippet, make 'I run!' to "I run!" and it'll work. Commented Apr 27, 2012 at 18:41
  • You misspelled "script" and the quotes in your console.log are breaking up the string. Commented Apr 27, 2012 at 18:42
  • Ok ok sorry, i make a simple example on the fly, the real code is more complex. Commented Apr 27, 2012 at 18:50

2 Answers 2

1

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.

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

3 Comments

If is the only way :-(, this is a problem if the script have a document.write... I'm apply the code but it is dinamyc, i don't know the code before insert. The only way is replace /document.write[\s\t\n\r]*((.*))/ patterns by theParent.innerHTML(\1);
document.write is obscenely horrible.
Yeh, but i don't decide wath insert
0

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!\');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.