How to run a tags. That's how I'm receiving the data. There are more than 1 pair of those and I really rather not go through the trouble of trying to remove them. It doesn't look like eval() will like those tags either. – ForeverNoobie Feb 07 '13 at 21:46

  • @Ravindra hello world was just an example, the code is actually pretty complex. I just put in the alert to see if *anything* would execute. – ForeverNoobie Feb 07 '13 at 21:51
  • 3 Answers3

    0

    Look at JS eval() http://www.w3schools.com/jsref/jsref_eval.ASP

    When you get your response back, add it to the body, then use jquery to pull out the string and eval it.

    $.get( url, function(data) {
        var d = $('<div/>').appendTo($('body')).append(data);
        eval($('script', d).text());
        d.remove();
      }
    )
    

    '<div/>' is a literal, used to create a node (disposed of after being used) in the DOM, as a placeholder for your js code.

    The code above will work for multiple '<script/>' fragments, too.

    psychowood
    • 2,900
    • 1
    • 14
    • 14
    ilan berci
    • 3,883
    • 1
    • 16
    • 21
    0

    Make you server return the code without the script tag, then run it creating a function

    (new Function('alert("Hello World")'))()
    

    If you can't avoid the script tag before, you can remove it with a regular expression before applying

    var data = '<script type="text/javascript">alert("hello world")</script>';
    var regex = /<[^>]*script[^>]*>(.*)<\/[^>]*script[^>]*>/;
    data.replace(regex,"$1")
    

    or even splitting the string at specific characters (not a good choice, for obvious reasons: you mess the string, your code won't run anymore)

    var data = '<script type="text/javascript">alert("hello world")</script>';
    data.substr(31,data.length - 40);
    

    The first option is way better, performance wise.

    If you really want to execute the code using the whole string as-is, you just have to be sure that the library you are using is not escaping your code.

    psychowood
    • 2,900
    • 1
    • 14
    • 14
    • I can get it to work without the – ForeverNoobie Feb 07 '13 at 21:56
    • The other answer is what you need, then. I edited the pseudocode with working js, you can try it yourself. – psychowood Feb 07 '13 at 23:12
    0

    This works great for me as a substitute for

    <script></script>
    

    ... and works even in an HTML file loaded using AJAX!

    <img src="data:image/png;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=" onload="alert('test');this.parentNode.removeChild(this);" />
    

    Try it. It uses an images 'onload' call to run the internal javascript whenever the included-by-data-uri, one-pixel image is loaded.

    Venryx
    • 15,624
    • 10
    • 70
    • 96