How do I safely “eval” user code in a webpage?

后端 未结 5 795
难免孤独
难免孤独 2020-12-16 01:19

I\'m working on a webapp to teach programming concepts. Webpages have some text about a programming concept, then let the user type in javascript code into a text editor wi

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 01:57

    Not clear if the eval() occurs on client or server side. For client side:

    • I think it's possible to eval safely in an well configured iframe (https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/)

    • This should be 100% safe, but needs a couple of libraries and has some limitations (no es6 support): https://github.com/NeilFraser/JS-Interpreter

    • There are lighter alternatives but not 100% safe like https://github.com/commenthol/safer-eval.

    • Alternatively, I think something similar can be implemented manually wrapping code in a with statement, overriding this, globals and arguments. Although it will never be 100% safe maybe is viable in your case.

提交回复
热议问题