EDIT: этот ответ не скрывает переменные window.something. Но у него есть чистый способ запуска пользовательского кода. Я пытаюсь найти способ маскировать переменные окна
Вы можете использовать функцию javascript Function.prototype.bind () , чтобы привязать функцию, представленную пользователем к настраиваемой переменной области видимости по вашему выбору, в этой настраиваемой области вы можете выбрать, какие переменные должны делиться с пользовательской функцией и скрывать. Для пользовательских функций код сможет получить доступ к переменным, которые вы использовали, используя this.variableName. Вот пример, чтобы подробно остановиться на идее:
// A couple of global variable that we will use to test the idea
var sharedGlobal = "I am shared";
var notSharedGlobal = "But I will not be shared";
function submit() {
// Another two function scoped variables that we will also use to test
var sharedFuncScope = "I am in function scope and shared";
var notSharedFuncScope = "I am in function scope but I am not shared";
// The custom scope object, in here you can choose which variables to share with the custom function
var funcScope = {
sharedGlobal: sharedGlobal,
sharedFuncScope: sharedFuncScope
};
// Read the custom function body
var customFnText = document.getElementById("customfn").value;
// create a new function object using the Function constructor, and bind it to our custom-made scope object
var func = new Function(customFnText).bind(funcScope);
// execute the function, and print the output to the page.
document.getElementById("output").innerHTML = JSON.stringify(func());
}
// sample test function body, this will test which of the shared variables does the custom function has access to.
/*
return {
sharedGlobal : this.sharedGlobal || null,
sharedFuncScope : this.sharedFuncScope || null,
notSharedGlobal : this.notSharedGlobal || null,
notSharedFuncScope : this.notSharedFuncScope || null
};
*/
Add your custom body here
В следующем примере: