Mozilla’s Content Security Policy disallows the use of javascript eval function as well as inline scripts. They claim that all instances of eval can be replaced by another (hopefully safer) function. I agree in most scenarios, Javascript eval can be replaced, but I’m not sure whether the replacement is possible for every case.
My question is twofold:
- Is there a generic way to replace every javascript eval function? (doesn’t have to be safe)
- Is there a case where the Javascript eval cannot be replaced?
The most common uses which can be substituted are the following ones. I would certainly use these first.
Accessing dynamic properties
Do use:
obj[keyAsVariable]Don’t use
eval('obj.' + keyAsVariable)Parsing JSON
Do use
JSON.parse(data)Don’t use
eval('(' + data + ')')Calculating user input
Do use a certain library
Don’t use
eval(input)If really necessary, you can also send the script to a server which simply echoes it back, and you can request it as a script tag. It won’t use
evalbut still execute it. It isn’t safe as it’s sent twice over the Internet.request_scriptcould be a file implemented in PHP, like the following. Again, it’s bad practice but is a generic way of circumventingeval.You could say that this also automatically answers your second question with ‘no’.