'How do i replace eval
I have some existing code that looks like this.
i = new Function("obj", "_", s);
The parameter s contains an executable javascript code, as a string. At a later point in the method, it gets called like
i.call(this, e, v)
I get a csp error for unsafeeval for the new Function line. How do I resolve this such that the unsafe eval does not come up again? Please help.
Basically what I'm trying to do is, I have a third party application which I have localised to fix the eval errors for CSP.
Why does the new Function cause the unsafe-eval error?
Solution 1:[1]
As @James mentioned, new Function("obj", "_", s)
evaluates the s
part, and generates a function based on the string.
It really depends on what's the s
here. Is it dynamically calculated?
- If no, then you can just copy the
s
as a real code:
const i = function(obj, _) {
// paste s here
}
- If yes, you will have to explicitly list all possible implementations. For example:
const i = function(obj, _) {
if (xxx) {
// implementation 1
} else if (xxx) {
// implementation 2
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | zzz |