Is It Possible to Sandbox JavaScript Running In the Browser?

I'm wondering if it's possible to sandbox JavaScript running in the browser to prevent access to features that are normally available to JavaScript code running in an HTML page.

For example, let's say I want to provide a JavaScript API for end users to let them define event handlers to be run when "interesting events" happen, but I don't want those users to access the properties and functions of the window object. Am I able to do this?

In the simplest case, let's say I want to prevent users calling alert. A couple of approaches I can think of are:

  • Redefine window.alert globally. I don't think this would be a valid approach because other code running in the page (i.e. stuff not authored by users in their event handlers) might want to use alert.
  • Send the event handler code to the server to process. I'm not sure that sending the code to the server to process is the right approach because the event handlers need to run in the context of the page.

Perhaps a solution where the server processes the user defined function and then generates a callback to be executed on the client would work? Even if that approach works are there better ways to solve this problem?

Google Caja is a source-to-source translator that "allows you to put untrusted third-party HTML and JavaScript inline in your page and still be secure."

Have a look at Douglas Crockford's ADsafe:

ADsafe makes it safe to put guest code (such as third party scripted advertising or widgets) on any web page. ADsafe defines a subset of JavaScript that is powerful enough to allow guest code to perform valuable interactions, while at the same time preventing malicious or accidental damage or intrusion. The ADsafe subset can be verified mechanically by tools like JSLint so that no human inspection is necessary to review guest code for safety. The ADsafe subset also enforces good coding practices, increasing the likelihood that guest code will run correctly.

You can see an example of how to use ADsafe by looking at the template.html and template.js files in the project's GitHub repository.

I created a sandboxing library called jsandbox that uses web workers to sandbox evaluated code. It also has an input method for explicitly giving sandboxed code data it wouldn't otherwise be able to get.

The following is an example of the API:

      code    : "x=1;Math.round(Math.pow(input, ++x))",
      input   : 36.565010597564445,
      callback: function(n) {
          console.log("number: ", n); // number: 1337
      code   : "][];.]\\ (*# ($(! ~",
      onerror: function(ex) {
          console.log("syntax error: ", ex); // syntax error: [error object]
      code    : '"foo"+input',
      input   : "bar",
      callback: function(str) {
          console.log("string: ", str); // string: foobar
      code    : "({q:1, w:2})",
      callback: function(obj) {
          console.log("object: ", obj); // object: object q=1 w=2
      code    : "[1, 2, 3].concat(input)",
      input   : [4, 5, 6],
      callback: function(arr) {
          console.log("array: ", arr); // array: [1, 2, 3, 4, 5, 6]
      code    : "function x(z){this.y=z;};new x(input)",
      input   : 4,
      callback: function(x) {
          console.log("new x: ", x); // new x: object y=4

I think that js.js is worth mentioning here. It's a JavaScript interpreter written in JavaScript.

It's about 200 times slower than native JS, but its nature makes it a perfect sandbox environment. Another drawback is its size – almost 600 kb, which may be acceptable for desktops in some cases, but not for mobile devices.

As mentioned in other responces, it's enough to jail the code in sandboxed iframe (without sending it to the server-side) and communicate with messages. I would suggest to take a look at a small library I created mostly because of the need to providing some API to the untrusted code, just like as described in the question: there's an opportunity to export the particular set of functions right into the sandbox where the untrusted code runs. And there's also a demo which executes the code submitted by a user in a sandbox:

An improved version of @RyanOHara's web workers sandbox code, in a single file (no extra eval.js file is necessary).

function safeEval(untrustedCode)
    return new Promise(function (resolve, reject)

    var blobURL = URL.createObjectURL(new Blob([
        function ()
            var _postMessage = postMessage;
            var _addEventListener = addEventListener;

            (function (obj)
                "use strict";

                var current = obj;
                var keepProperties = [
                    // required
                    'Object', 'Function', 'Infinity', 'NaN', 'undefined', 'caches', 'TEMPORARY', 'PERSISTENT', 
                    // optional, but trivial to get back
                    'Array', 'Boolean', 'Number', 'String', 'Symbol',
                    // optional
                    'Map', 'Math', 'Set',

                do {
                    Object.getOwnPropertyNames(current).forEach(function (name) {
                        if (keepProperties.indexOf(name) === -1) {
                            delete current[name];

                    current = Object.getPrototypeOf(current);
                while (current !== Object.prototype);

            _addEventListener("message", function (e)
            var f = new Function("", "return (" + + "\n);");
        ")()"], {type: "application/javascript"}));

    var worker = new Worker(blobURL);


    worker.onmessage = function (evt)

    worker.onerror = function (evt)
        reject(new Error(evt.message));


    setTimeout(function () {
        reject(new Error('The worker timed out.'));
        }, 1000);

Test it:

var promise = safeEval("1+2+3");

promise.then(function (result) {

It should output 6 (tested in Chrome and Firefox).

All the browser vendors and the HTML5 specification are working towards an actual sandbox property to allow sandboxed iframes -- but it's still limited to iframe granularity.

In general, no degree of regular expressions, etc. can safely sanitise arbitrary user provided JavaScript as it degenerates to the halting problem :-/

An ugly way but maybe this works for you , I took all the globals and redefined them in the sandbox scope , as well I added the strict mode so they can't get the global object using an anonymous function.

function construct(constructor, args) {
  function F() {
      return constructor.apply(this, args);
  F.prototype = constructor.prototype;
  return new F();
// Sanboxer 
function sandboxcode(string, inject) {
  "use strict";
  var globals = [];
  for (var i in window) {
    if (i != "console")
  globals.push('"use strict";\n'+string);
  return construct(Function, globals).apply(inject ? inject : {});
sandboxcode('console.log( this, window, top , self, parent, this["jQuery"], (function(){return this;}()));'); 
// => Object {} undefined undefined undefined undefined undefined undefined 
console.log("return of this", sandboxcode('return this;', {window:"sanboxed code"})); 
// => Object {window: "sanboxed code"}

An independent Javascript interpreter is more likely to yield a robust sandbox than a caged version of the builtin browser implementation. Ryan has already mentioned js.js, but a more up-to-date project is JS-Interpreter. The docs cover how to expose various functions to the interpreter, but its scope is otherwise very limited.

As of 2019, vm2 looks like the most popular and most regularly-updated solution to this problem.

1) Suppose you have a code to execute:

var sCode = "alert(document)";

Now, suppose you want to execute it in a sandbox:

new Function("window", "with(window){" + sCode + "}")({});

These two lines when executed will fail, because "alert" function is not available from the "sandbox"

2) And now you want to expose a member of window object with your functionality:

new Function("window", "with(window){" + sCode + "}")({
    'alert':function(sString){document.title = sString}

Indeed you can add quotes escaping and make other polishing, but I guess the idea is clear.

Where is this user JavaScript coming from?

There is not much you can do about a user embedding code into your page and then calling it from their browser (see Greasemonkey, It's just something browsers do.

However, if you store the script in a database, then retrieve it and eval() it, then you can clean up the script before it is run.

Examples of code that removes all window. and document. references:

    .replace(/\/\/.+\n|\/\*.*\*\/, '') // Clear all comments
    .replace(/\s(window|document)\s*[\;\)\.]/, '') // removes window. or window; or window)

This tries to prevent the following from being executed (not tested):

window.location = '';
var w = window  ;

There are a lot of limitations you would have to apply to the unsafe user script. Unfortunately, there is no 'sandbox container' available for JavaScript.

I've been working on a simplistic js sandbox for letting users build applets for my site. Although I still face some challenges with allowing DOM access (parentNode just won't let me keep things secure =/), my approach was just to redefine the window object with some of its useful/harmless members, and then eval() the user code with this redefined window as the default scope.

My "core" code goes like this... (I'm not showing it entirely ;)

function Sandbox(parent){

    this.scope = {
        window: {
            alert: function(str){
                alert("Overriden Alert: " + str);
            prompt: function(message, defaultValue){
                return prompt("Overriden Prompt:" + message, defaultValue);
            document: null,

    this.execute = function(codestring){

        // here some code sanitizing, please

        with (this.scope) {
            with (window) {

So, I can instance a Sandbox and use its execute() to get code running. Also, all new declared variables within eval'd code will ultimately bound to the execute() scope, so there will not be clashing names or messing with existing code.

Although global objects will still be accesible, those which should remain unknown to the sandboxed code must be defined as proxies in the Sandbox::scope object.

Hope this works for you.

You can wrap the user's code in a function that redefines forbidden objects as parameters -- these would then be undefined when called:

(function (alert) {

alert ("uh oh!"); // User code

}) ();

Of course, clever attackers can get around this by inspecting the Javascript DOM and finding a non-overridden object that contains a reference to the window.

Another idea is scanning the user's code using a tool like jslint. Make sure it's set to have no preset variables (or: only variables you want), and then if any globals are set or accessed do not let the user's script be used. Again, might be vulnerable to walking the DOM -- objects that the user can construct using literals might have implicit references to the window object that could be accessed to escape the sandbox.

With NISP you'll be able to do sandboxed evaluation. Though the expression you write is not exactly a JS, instead you'll write s-expressions. Ideal for simple DSLs that doesn't demand extensive programming.