Javascript eval的替代品 [英] Alternatives for Javascript eval
问题描述
我的问题是双重的:
- 是否有一种通用的方法来替换每个JavaScript的eval函数? (不一定要安全)
- 有没有一种情况下Javascript的eval不能被替换?
可以替代的最常见的用法如下。
-
访问动态属性
使用:
obj [keyAsVariable]
不要使用
eval('obj。 '+ keyAsVariable)
-
解析JSON
不要使用
eval('('+ data + ')')
-
计算用户输入
某些图书馆
不要使用<
$如果真的有必要,你也可以发送脚本到一个服务器,只是简单的回声,你可以请求它作为脚本标记。它不会使用eval
但仍然执行它。这是不安全的,因为它是通过互联网发送两次。
$ $ p $ $ c $ var s = document.createElement('script')
s.src ='request_script?data ='+ data;
document.getElementsByTagName('head')[0] .appendChild(s);
request_script
,如下所示。再一次,这是不好的做法,但是是一种规避eval
的通用方法。
< ;?
echo $ _GET ['data'];
?>
你也可以这么说,这也自动地回答你的第二个问题。 b $ b
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
eval
but still execute it. It isn't safe as it's sent twice over the Internet.var s = document.createElement('script') s.src = 'request_script?data=' + data; document.getElementsByTagName('head')[0].appendChild(s);
request_script
could be a file implemented in PHP, like the following. Again, it's bad practice but is a generic way of circumventingeval
.<? echo $_GET['data']; ?>
You could say that this also automatically answers your second question with 'no'.
这篇关于Javascript eval的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!