8

Some claim eval is evil.

Any regular HTML page may look like:

        <script src="some-trendy-js-library.js"></script>
    </body>
</html>

That is, assuming the person doing this knows his job and leaves javascript to load at the end of the page.

Here, we are basically loading a script file into the web browser. Some people have gone deeper and use this as a way to communicate with a 3rd party server...

<script src="//foo.com/bar.js"></script>

At this point, it's been found important to actually load those scripts conditionally at runtime, for whatever reason.

What is my point? While the mechanics differ, we're doing the same thing...executing a piece of plain text as code - aka eval().


Now that I've made my point clear, here goes the question...

Given certain conditions, such as an AJAX request, or (more interestingly) a websocket connection, what is the best way to execute a response from the server?

Here's a couple to get you thinking...

  • eval() the server's output. (did that guy over there just faint?)
  • run a named function returned by the server: var resp = sock.msg; myObj[resp]();
  • build my own parser to figure out what the server is trying to tell me without messing with the javascript directly.
4

5 に答える 5

5

AJAX リクエストや (もっと興味深いことに) Websocket 接続などの特定の条件が与えられた場合、サーバーからの応答を実行する最良の方法は何ですか?

メッセージの結果を解析する際の主な批判はeval、やり過ぎだということです。強力なツールに起因するすべての余分なリスクを伴う大ハンマーを使用してハエをたたきます。

応答の種類をいくつかの異なるカテゴリに分けてみましょう。

  1. オンデマンドで読み込まれる静的な JavaScript
  2. 信頼できない関係者によって指定されたコンテンツを含まない、安全なチャネル上の信頼できるソースからの動的な応答。
  3. ほとんどがデータである混合ソースからの動的応答 (ほとんどが信頼されている可能性がありますが、信頼されていない当事者によって指定されたエンコードされた文字列が含まれています)
  4. データに基づく副作用

eval(1)については、XHR+とに違いはありません<script src>が、XHR+evalの利点はほとんどありません。

(2)については、ほとんど違いはありません。を使用して応答を解凍できる場合JSON.parse、問題が発生するeval可能性は低くなりますが、信頼できるソースからのデータで の余分な権限が悪用される可能性は低いため、十分な肯定的な理由がある場合は大したことではありません。eval.

(3)に関しては、大きな違いがあります。 evalの超悪用可能な権限は、たとえあなたが細心の注意を払っていても、あなたを噛む可能性があります. これはセキュリティ的に脆弱です。やらないでください。

(4)については、データの問題とコードの問題に分けられると良いです。実行前に結果を検証できる場合、JSONP はこれを許可します。悪用可能な権限がほとんどないものを使用してデータを解析するため、作成しJSON.parseて外部使用を承認した関数が副作用を行います。これにより、過剰な悪用可能な権限が最小限に抑えられます。ここでナイーブevalは危険です。

于 2012-02-13T19:19:56.213 に答える