Background: I\'m working on a framework/library to be used for a specific site in coordination with greasemonkey/userscripts. This framework/library will al
There's no absolute way to prevent an end user or addon developer from executing specific code in JavaScript. That's why security measures in an open source language like JavaScript is said to be foolproof (as in it's only effective against fools).
That being said however let's build a sandbox security layer to prevent inexperienced developers from breaking your site. Personally I prefer using the Function
constructor over eval
to execute user code for the following reasons:
jQuery
).this
pointer and create local variables named window
and document
to prevent access to the global scope and the DOM. This allows you to create your own version of the DOM and pass it to the user code.Note however that even this pattern has disadvantages. Most importantly it may only prevent direct access to the global scope. User code may still create global variables by simply declaring variables without var
, and malicious code may use hacks like creating a function and using it's this
pointer to access the global scope (the default behavior of JavaScript).
So let's look at some code: http://jsfiddle.net/C3Kw7/