I was making (not now, but still interesting to me) a game using HTML5 and JS, and I wanted people to be able to insert a custom script, but safe.
function executeCustomJS(code){ eval(code);
Of course, this code is very bad, because if the code is something like document.location.href='http://meatspn.com' , then the result will be very ... (...)
One of the solutions I found is to escape (for example, eval → ___eval___ ) all keywords and exclude keywords in the white list, such as "while", "for", "if", "var", true ',' false ', ... and 'func0', 'func1', .... which are a bit of an API and safe.
For example,
function executeCustomJS(code){ code = code.replace(/(Keyword RegEx)/g,'___$1___'); eval(code); }
I did not do RegEx and things in the comments, but that is not a question.
Suppose that the lines in the code are not escaped, there is no function that can be performed by escaping the lines, and "eval", "window", "document", "alert", "location" are NOT whitelisted. Nevertheless, some people can execute code like while(true){} , they cannot execute any code, for example document.location.href='http://meatspn.com' .
Is this method safe? Or, is there a better way or not?
javascript security eval xss
Jiminp
source share