Javascript eval的替代品 [英] Alternatives for Javascript eval

查看:162
本文介绍了Javascript eval的替代品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mozilla的内容安全策略不允许使用JavaScript eval函数,以及内联脚本。他们声称eval的所有实例都可以被另一个(希望更安全)的函数取代。我同意在大多数情况下,JavaScript的eval可以取代,但我不知道是否可以替代每个案件。



我的问题是双重的:


  1. 是否有一种通用的方法来替换每个JavaScript的eval函数? (不一定要安全)

  2. 有没有一种情况下Javascript的eval不能被替换?


解决方案

可以替代的最常见的用法如下。


  1. 访问动态属性



    使用: obj [keyAsVariable]



    不要使用 eval('obj。 '+ keyAsVariable)


  2. 解析JSON



    不要使用 eval('('+ data + ')')


  3. 计算用户输入

    某些图书馆



    不要使用<





    $如果真的有必要,你也可以发送脚本到一个服务器,只是简单的回声,你可以请求它作为脚本标记。它不会使用 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:

    1. Is there a generic way to replace every javascript eval function? (doesn't have to be safe)
    2. 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.

    1. Accessing dynamic properties

      Do use: obj[keyAsVariable]

      Don't use eval('obj.' + keyAsVariable)

    2. Parsing JSON

      Do use JSON.parse(data)

      Don't use eval('(' + data + ')')

    3. 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 circumventing eval.

    <?
    echo $_GET['data'];
    ?>
    

    You could say that this also automatically answers your second question with 'no'.

    这篇关于Javascript eval的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆