Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sandbox sample
/**
* Compile the given inlined code to valid javascript,
* wraped into an iframe as execution context
*/
function createSandboxedStatements(args) {
// Save arguments into local constants for further usage and defaults
const code = args.code || "";
const parameters = args.parameters || [];
// Create iframe
sandboxFrame = document.createElement("iframe");
document.body.appendChild(sandboxFrame);
// Update the attributes, no matter if the element is existing or not
sandboxFrame.src = "data:text/html;";
sandboxFrame.sandbox = "allow-scripts allow-same-origin";
sandboxFrame.style.display = "none";
// Create function with iframe as execution context
const sandboxFunction = new sandboxFrame.contentWindow.Function(
...parameters,
`'use strict'; ${code}`
);
// Remove iframe from dom
sandboxFrame.remove();
// Dereference iframe
sandboxFrame = null;
// Return wrapped sandbox function
return sandboxFunction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment