3
votes

I have used eval but disallowing it by applying CSP. But I am looking for an alternative to it.

I found the function jQuery.globaleval().

jQuery.readyException = function( error ) {
    window.setTimeout( function() {
        throw error; 
    });
};

throws:

Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' http://localhost:6060/WCUSTODY/ http://localhost:6060/application/scripts

So, can we use global eval as an alternative to eval, should also accepted by CSP (Content Security Policy).

1
Why would that code you provided use eval and throw that error?epascarello
Have you read the documentation for jQuery.globalEval()? You'll note they specifically talk about using a nonce for CSP...Heretic Monkey

1 Answers

0
votes

jQuery.globaleval() behaves differently from using a normal JavaScript eval() in that it's executed within the global context. For example

function test() {
  jQuery.globalEval( "var newVar = true;" );
}
test();

The variable called newVar is in the scope of global. It can be accessed accross the script of your application.

You can use eval() without jQuery.globaleval() in CSP by setting unsafe-eval as a allowed source.

Similar to like this:

<meta http-equiv="Content-Security-Policy" content="script-src 'unsafe-eval'">

If you don't want to use the eval then you can use new Function(). By best practices you should avoid eval() and new Function()