背景:我正在为一个特定的网站与Greasemonkey / Userscripts协调使用的框架/库工作。这个框架/库将允许插件支持。其工作方式是插件通过列表在库中注册所需的页面、资源等,库将等待满足所有条件后调用插件的load()
函数。
问题:在这个“必需内容”的列表中,我希望插件开发人员能够指定要评估为“必需资源”的javascript(作为字符串)。例如'document.getElementById("banana")'
。我想做的是对“必需资源”的评估进行半沙盒化,以便评估可以访问window和DOM对象,但不能直接更改它们。我还希望使eval和evalJS无法从沙盒中访问。
示例:
document.getElementById("banana")
->有效document.getElementById("apple).id = "orange"
->无效window.grape
->有效window.grape = 'potato'
->无效(someObj.applesCount > 0 ? 'some' : 'none')
->有效
到目前为止我所做的:
function safeEval(input) {
// Remove eval and evalJS from the window:
var e = [window.eval, window.evalJS], a;
window.eval = function(){};
window.evalJS = function(){};
try {
/* More sanition needed before being passed to eval */
// Eval the input, stuffed into an annonomous function
// so the code to be evalued can not access the stored
// eval functions:
a = (e[0])("(function(){return "+input+"}())");
} catch(ex){}
// Return eval and evalJS to the window:
window.eval = e[0];
window.evalJS = e[1];
// Return the eval'd result
return a;
}
注意事项:
这是一个Greasemonkey/userscript。我没有直接修改该网站或其javascript的访问权限。
safeEval()
的输入可以是任何有效的javascript,可以是DOM查询或简单的计算,只要不更改窗口对象或DOM即可。
@require
指令和一些GM_xhr调用到他们的API。不确定Caja是否符合您的要求。 - Brock Adamswindow
和document
,您有什么想法?这样,属性就可以被更改,但是您之后可以恢复原始的 DOM。不过可能会影响性能。 - Platinum Azure