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.
The main criticism of
evalwhen used to parse message results is that it is overkill — you are using a sledgehammer to swat a fly with all the extra risk that comes from overpowered tools — they can bounce back and hit you.Let’s break the kinds of responses into a few different categories:
For (1), there is no difference between XHR+
evaland<script src>, but XHR+evalhas few advantages.For (2), little difference. If you can unpack the response using
JSON.parseyou are likely to run into fewer problems, buteval‘s extra authority is less likely to be abused with data from a trusted source than otherwise so not a big deal if you’ve got a good positive reason foreval.For (3), there is a big difference.
eval‘s extra-abusable authority is likely to bite you even if you’re very careful. This is brittle security-wise. Don’t do it.For (4), it’s best if you can separate it into a data problem and a code problem. JSONP allows this if you can validate the result before execution. Parse the data using
JSON.parseor something else with little abusable authority, so a function you wrote and approved for external use does the side-effects. This minimizes the excess abusable authority. Naiveevalis dangerous here.