Skip to content

Instantly share code, notes, and snippets.

@OMGZui
Created October 26, 2022 11:25
Show Gist options
  • Save OMGZui/033cafeeb446b9e86c4303b5d81d110e to your computer and use it in GitHub Desktop.
Save OMGZui/033cafeeb446b9e86c4303b5d81d110e to your computer and use it in GitHub Desktop.
class SandboxGlobalProxy {
constructor(sharedState) {
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 (sharedState.includes(prop)) {
return false;
}
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 maybeAvailableSandbox(code, ctx) {
withedYourCode(code).call(ctx, ctx);
}
const code = `
console.log(history == window.history) // false
window.abc = 'sandbox'
Object.prototype.toString = () => {
console.log('Traped!')
}
console.log(window.abc) // sandbox
`;
const sharedGlobal = ["history"];
const globalProxy = new SandboxGlobalProxy(sharedGlobal);
maybeAvailableSandbox(code, globalProxy);
console.log(window.abc); // undefined
Object.prototype.toString();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment