Safe usage of eval() on server-sent JavaScript code

前端 未结 1 855
太阳男子
太阳男子 2020-12-10 13:53

I\'m using Node.js and Socket.io. I\'ve written an application which can send JavaScript snippets from the server and execute them on the client. The JavaScript is sent via

相关标签:
1条回答
  • 2020-12-10 14:33

    eval(), even if you have legit use, is just dangerous. You should avoid using it at all costs. use it with care.

    However, if it's really needed, then you can use strict mode via "use strict" command. When eval() is executed in a strict function, the eval's content will not leak in the immediate scope. The code in an eval will be contained in eval() itself (as if it has it's own scope). In the demo, try removing the trailing x and eval() will return undefined.

    But still, using eval() is dangerous. It's better if you find alternatives like JSON with custom string commands that will be parsed client-side.

    0 讨论(0)
提交回复
热议问题