Running dynamic Javascript code -


i'm making small game , part of want simple custom programming language. if user enters code, variable "helloworld" = 5, "interpreter" change variable var , drop quotes normal javascript.

how should run code? i've read eval(), i've read it's slow , shouldn't used. i've looked creation of programming languages lexers, parsers, , tokenizers, i'm not looking create in-depth.

any direction great.

i assume don't need "how write code?", how execute user script.

about eval:

  1. is eval slow? yes. how slow slow? if script runs in 10ms compiled , 20ms otherwise, problem , application?
  2. could user mess eval? yes! reassign functions, globals, etc. accidentally break page.
  3. is dangerous? yes! become vulnerable xss attacks. have sensitive data? have server side application? if not, think eval ok.

here more information different questions:

an idea preventing global reassignment

wrap script in iife! wrap script this:

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

javascript has function scope protect global space getting filled user variables , functions. users still maliciously affect global variables this:

(function(){array.isarray = function() { return 2;};})() array.isarray([]); // returns 2     

more speed of eval. real example:

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

output:

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

as can see 'big-eval' little slower. big-eval, running lines of user script @ once. 'evil-eval' slower because js engine running eval 10,000,000 times! :)


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -