Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternatives to eval for running remote code

Are there any alternatives to using eval to immediatly run remote & trusted javascript code.

function load(filePath) {
    var o = $.ajax({
        url: filePath,
        dataType: 'html',
        async: false 
    }); 

    eval(o.responseText);
}

load("somePath");
// run a function that relies on the code from o.responseText being loaded
doSomethingWithCode();

I'm aware that synchronous loading of javascript is adviced againts. But if there is no choice are there any cross browser alternatives for the use of eval above.

[Edit]

To clarify in more detail the code being loaded is a self executing function. Which needs to execute before doSomethingWidthCode. It's also being loaded from the server on the same domain hence its trusted.

like image 253
Raynos Avatar asked Oct 31 '25 15:10

Raynos


1 Answers

Dynamic script text insertion is the only alternative to eval.

var head    = document.getElementsByTagName('head')[0] || document.documentElement,
    nscr    = document.createElement('script');

    nscr.type           = 'text/javascript';
    nscr.textContent    = o.responseText;
    nscr.setAttribute('name', 'dynamically inserted');
    nscr.onload         = nscr.onreadystatechange = function() {
              if( nscr.readyState ) {
                   if( nscr.readyState === 'complete' || scr.readyState === 'loaded' ) {
                      nscr.onreadystatechange = null;
                       doSomethingWithCode();
              }
              else {
                  doSomethingWithCode();
              }
    };

    head.insertBefore(nscr, head.firstChild);

Only thing to mention: textContent is not available in InternetExplorers. You would need to use .text instead there, so a little detection for that makes it cross-browser compatible.

edit

To have a syncronous loading dynamic script tag, you could add nscr.async = true;. Anyway, this only works in cutting edge browsers.

like image 152
jAndy Avatar answered Nov 03 '25 06:11

jAndy