My code is not unsafe(-eval)

I was working on a project this week when I came across something which confused me, and that was the following error in my browser console…

Refused to evaluate a string as JavaScript because ‘unsafe-eval’ is not an allowed source of script in the following Content Security Policy directive: ‘self’

In itself, not massively odd.  I certainly had a Content Security Policy (or CSP) in place on this project (as should you on your next project!), and I had in fact set “script-src” to be ‘self’.  But I wasn’t using (evil) eval anywhere, so what could be triggering it?

Well I was being pointed to a line of javascript in one of my own javascript files.  This was increasingly odd as this was self-hosted and therefore should absolutely have fallen into the realms of ‘self’.

The offending line was this one…

setTimeout(show_progress(ttl,val2,fnc),wait);

Now was exactly it was doing doesn’t really matter, but the point is that the setTimeout was taking the first parameter, and essentially doing an eval on it, triggering the CSP error.  This must just be how setTimeout works, which I’d never really stopped to think about before.

The solution (don’t change the CSP is allow ‘unsafe-eval’!) was to wrap the first parameter in an anonymous function, like this…

setTimeout(function() {
  show_progress(ttl,val2,fnc);
},wait);

This now means that setTimeout is getting a function passed as the first parameter, which it runs properly instead of trying to eval.

So I will endeavour to always do this from now on – make sure that I’m not accidentally including eval in my code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.