在Javascript中围绕Function()创建沙箱 [英] Make sandbox around Function() in Javascript

查看:73
本文介绍了在Javascript中围绕Function()创建沙箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以限制字符串生成函数(使用Function构造函数)对父/全局范围的访问吗?

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

例如:以下代码,如它是,打印 false ,因为该函数正在窗口中存储/修改变量a。

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);

我可以限制对窗口/父作用域的访问并使其打印出来true

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

推荐答案

这是一个额外的想法,可以与Esailija的提案一起发挥得非常强大(见他的评论)回答讨论)。

Here is an additional idea which could be quite powerful together with Esailija's proposal (see the comments on his answer for the discussion).

您可以创建虚拟iframe并使用其函数函数。使用它创建的函数默认只能访问iframe的范围,尽管它仍然可以突破它。幸运的是,就像Esailija建议的那样,很容易防止这种情况。

You could create dummy iframe and use its Function function. The function created with that will only have access to the scope of the iframe by default, though it could still break out of it. Fortunately it is easy to prevent that, by the way Esailija suggested.

我可以想象这个函数是这样的:

I could imagine the function to be like this:

function sandboxed(code) {
    var frame = document.createElement('iframe');
    document.body.appendChild(frame);

    var F = frame.contentWindow.Function,
        args = Object.keys(frame.contentWindow).join();

    document.body.removeChild(frame);

    return F(args, code)();
}

DEMO

您可能希望预先添加'use strict'; 代码。

Optionally you might want to prepend 'use strict'; to the code.

这至少在Chrome中起作用。以这种方式创建的函数是否可以访问iframe的全局范围,或者页面的全局范围可以通过以下方式轻松测试:

This works at least in Chrome. Whether the function created this way has access to the iframe's global scope or the page's global scope can be easily tested with:

(function() {
    var frame = document.createElement('iframe');
    document.body.appendChild(frame);
    var same = window === frame.contentWindow.Function('return window;')();
    alert(same ? ':(' : ':)');
    document.body.removeChild(frame);
}());

这篇关于在Javascript中围绕Function()创建沙箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆