Skip to content

Instantly share code, notes, and snippets.

@OMGZui
Created October 26, 2022 11:27
Show Gist options
  • Save OMGZui/ba0de4b5650372e8392d5b228243ecfe to your computer and use it in GitHub Desktop.
Save OMGZui/ba0de4b5650372e8392d5b228243ecfe to your computer and use it in GitHub Desktop.
class SandboxGlobalProxy {
constructor(blacklist) {
const iframe = document.createElement("iframe", { url: "about:blank" });
iframe.style.display = "none";
document.body.appendChild(iframe);
const sandboxGlobal = iframe.contentWindow;
return new Proxy(sandboxGlobal, {
has: (target, prop) => {
if (blacklist.includes(prop)) {
throw new Error(`Can't use: ${prop}!`);
}
if (!target.hasOwnProperty(prop)) {
throw new Error(`Not find: ${prop}!`);
}
return true;
}
});
}
}
function withedYourCode(code) {
code = "with(sandbox) {" + code + "}";
return new Function("sandbox", code);
}
function makeSandbox(code, ctx) {
withedYourCode(code).call(ctx, ctx);
}
const code = `console.log(document)`;
const blacklist = ['window', 'document', 'XMLHttpRequest', 'fetch', 'WebSocket', 'Image'];
const globalProxy = new SandboxGlobalProxy(blacklist);
makeSandbox(code, globalProxy);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment