は、多分それは少し
お手伝いを致します
function RestrictFunction(params) {
params = (params == undefined ? {} : params);
var scope = (params.scope == undefined ? window : params.scope);
var data = (params.data == undefined ? {} : params.data);
var script = (params.script == undefined ? '' : params.script);
if (typeof params.script == 'function') {
script = params.script.toString();
script = script.substring(script.indexOf("{") + 1, script.lastIndexOf("}"));
}
// example: override native functions that on the white list
var setTimeout = function(_function,_interval) {
// this is important to prevent the user using `this` in the function and access the DOM
var interval = scope.setTimeout(function() {
RestrictFunction({
scope:scope,
data:data,
script:_function
});
} , _interval);
// Auto clear long user intervals
scope.setTimeout(function() {
scope.clearTimeout(interval);
} , 60*1000);
return interval;
}
// example: create custom functions
var trace = function(str) {
scope.console.log(str);
}
return (function() {
// remove functions, objects and variables from scope
var queue = [];
var WhiteList = [
"Blob","Boolean","Date","String","Number","Object","Array","Text","Function",
"unescape","escape","encodeURI","encodeURIComponent","parseFloat","parseInt",
"isNaN","isFinite","undefined","NaN",
"JSON","Math","RegExp",
"clearTimeout","setTimeout"
];
var properties = Object.getOwnPropertyNames(scope);
for (var k = 0; k<properties.length; k++) {
if (WhiteList.indexOf(properties[k])!=-1) continue;
queue.push("var "+properties[k]+" = undefined;");
}
for (var k in scope) {
if (WhiteList.indexOf(k)!=-1) continue;
queue.push("var "+k+" = undefined;");
}
queue.push("var WhiteList = undefined;");
queue.push("var params = undefined;") ;
queue.push("var scope = undefined;") ;
queue.push("var data = undefined;") ;
queue.push("var k = undefined;");
queue.push("var properties = undefined;");
queue.push("var queue = undefined;");
queue.push("var script = undefined;");
queue.push(script);
try {
return eval('(function(){'+ queue.join("\n") +'}).apply(data);');
} catch(err) { }
}).apply(data);
}
使用例
// dummy to test if we can access the DOM
var dummy = function() {
this.notify = function(msg) {
console.log(msg);
};
}
var result = RestrictFunction({
// Custom data to pass to the user script , Accessible via `this`
data:{
prop1: 'hello world',
prop2: ["hello","world"],
prop3: new dummy()
},
// User custom script as string or function
script:function() {
trace(this);
this.msg = "hello world";
this.prop3.notify(this.msg);
setTimeout(function() {
trace(this);
} , 10);
trace(data);
trace(params);
trace(scope);
trace(window);
trace(XMLHttpRequest);
trace(eval);
return "done!"; // not required to return value...
},
});
console.log("result:" , result);
可能性がありますが、確かに行うことができます一つのことがあるhttp://www.adsafe.org/ –
を見てみましょうとにかく一般的に良い方法であるグローバル変数を避けてください。 – Pointy
@Pointy:それでも、信頼できないコードがDOMにアクセスしたり、あなたのページを改ざんするのを防ぐことはできません。 – josh3736