运行动态Javascript代码 [英] Running dynamic Javascript code

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

问题描述

我正在做一个小游戏,在某种程度上,我想要一种非常简单的自定义编程语言.如果用户输入代码,例如变量"helloWorld" = 5 ,则解释器"会将变量更改为var并删除引号,使其成为普通的JavaScript.

I'm making a small game and for part of it I want a really simple custom programming language. If a user enters code, something like variable "helloWorld" = 5, the "interpreter" would change variable to var and drop the quotes to be normal JavaScript.

我应该如何运行该代码?我已经读过有关 eval()的内容,但我也读过它很慢,不应该使用.我已经研究过使用词法分析器,解析器和令牌化器创建编程语言的方法,但是我并不想深入地进行设计.

How should I run that code? I've read about eval(), but I've also read it's slow and shouldn't be used. I've looked into creation of programming languages with lexers, parsers, and tokenizers, but I'm not looking to create something that in-depth.

任何对方向的帮助都是很好的.

Any help with direction would be great.

推荐答案

我假设您不需要如何编写该代码?"方面的帮助,而是如何执行用户脚本.

I assume you don't need help with "How to write that code?", but how to execute the user script.

  1. 评估速度慢吗?是的.慢慢有多慢?如果脚本以10毫秒的编译时间运行,否则以20毫秒的速度运行,这对您和您的应用程序来说是一个问题吗?
  2. 用户是否可以评估eval?是的!他们可能会重新分配功能,全局变量等.他们可能会意外中断页面.
  3. 这很危险吗?是的!您可能会容易受到XSS攻击.您有任何敏感数据吗?您的应用程序是否有服务器端?如果没有,我认为 eval 没问题.

以下是来自不同SO问题的更多信息:

  • 在没有XSS威胁的情况下使用eval
  • JS评估安全问题
  • 将脚本包装在IIFE中!这样包装脚本:

    Wrap the script in an IIFE! Wrap the script like this:

    (function(){
    // user script goes here.  This will cause it to be in it's own scope!
    })();
    

    JavaScript具有函数作用域,因此这将防止全局空间被用户变量和函数填充.用户仍然可以像这样恶意影响全局变量:

    Javascript has function scope so this will protect the global space from getting filled with user variables and functions. Users could still maliciously affect global variables like this:

    (function(){Array.isArray = function() { return 2;};})()
    Array.isArray([]);
    // returns 2    
    

    有关评估速度的更多信息.一个真实的例子:

    #!/bin/env node
    // Be careful running this.  You don't want to melt your cpu.  Try 100,000 first.
    console.time("no-eval"); 
    for (var i = 0; i < 10000000; i++) { Math.sqrt(i); }  
    console.timeEnd("no-eval");
    console.time("big-eval"); 
    eval("for (var i = 0; i < 10000000; i++) { Math.sqrt(i); }");
    console.timeEnd("big-eval");
    console.time("evil-eval"); 
    for (var i = 0; i < 10000000; i++) { eval("Math.sqrt(i);"); }  
    console.timeEnd("evil-eval");
    

    输出:

    no-eval: 272ms
    big-eval: 294ms
    evil-eval: 1945ms
    

    如您所见,大评估"要慢一些.您可能会进行一次大评估,一次运行用户脚本的所有行."evil-eval"要慢得多,因为js引擎运行eval 10,000,000次!:)

    As you can see the 'big-eval' is a little slower. You will probably do the big-eval, running all lines of the user script at once. The 'evil-eval' is much slower because the js engine is running the eval 10,000,000 times! :)

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

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