Make sandbox around Function() in Javascript

Viewed 2711

Can I limit the access of a string-generated function (using the Function constructor) to the parent/global scopes?

For example: the following code, as it is, prints false, because the function is storing/modifying the variable a in window.

window.a = 4;
Function("a=3;")()
console.log(a === 4);

Could I restrict the access to window/parent scope and make it print out "true"?

4 Answers

Here's my adapted sandboxed function. It takes code and an optional dictionary with arguments to the function.

function sandboxed(code, args = {}) {
    var frame = document.createElement('iframe');
    document.body.appendChild(frame);
    var F = frame.contentWindow.Function;
    document.body.removeChild(frame);
    return F(...Object.keys(args), "'use strict';" + code)(...Object.values(args));
}

console.log(sandboxed('return a - 10;', {'a': 34}));

// 24
Related