JSFiddle - React, Tailwind, and code Playground
HTML
<div id="banana">I am a banana!</div>
<div id="apple">Just an apple :(</div>
JavaScript
function safeEval(input) {
// Remove eval and evalJS from the window:
var e = [window.eval, window.evalJS, document.getElementById], a;
window.eval = function(){};
window.evalJS = function(){};
document.getElementById = function (id) {
var elem = (e[2]).call(document, id);
for (var prop in elem) {
if (elem.hasOwnProperty(prop)) {
elem.__defineGetter__(prop, function () {
return (function (val) {
return val;
}(elem[prop]));
});
}
}
return elem;
};
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];
document.getElementById = e[2];
// Return the eval'd result
return a;
}
window.onload = function () {
console.log(safeEval('document.getElementById("banana")'));
safeEval('document.getElementById("apple").id = "orange"');
console.log(safeEval('document.getElementById("orange")'));
};