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…


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() {

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.