How can I write a function accepting callBack function and run it in a 'safe' way?

pencilCake picture pencilCake · Apr 8, 2011 · Viewed 13.6k times · Source

I want to write such a function:

function doGoodJob(someId, callBackfunction){

// some stuff with someId

// todo: RUN callBackFunction here

}

They say eval is 'dangerous' in terms of code injection.

so, what is the best practice to write a JavaScript function that accepts a call-back function and runs it securely?

Answer

Richard Friend picture Richard Friend · Apr 8, 2011

Is your callback a string or an actual function ?

If its a function..

function doGoodJob(someId,callbackFunction)
{
     callbackFunction();
}

doGoodJob(1,function(){alert('callback');});

If its a string you can use the Function constructor.

function doGoodJob(someId,callbackFunction)
{
     var func = new Function(callbackFunction)
     func();
}
doGoodJob(1,"alert('test');");

Or test for both..

function doGoodJob(someId,callbackFunction)
{
    var func = (typeof callbackFunction == 'function') ?
        callbackFunction : new Function(callbackFunction);

     func();   
}

doGoodJob(1,function(){alert('callback');});
doGoodJob(1,"alert('test');");