Is there a safe way to run eval in a webpage and avoid it to access the content of the rest of the page?



I wonder if it is possible to run code provided by users in a webpage in a safe way.

I would like to add code that users can dynamically change to change some of the page behaviour, but I donĀ“t want them to use exploits.

For example, I would like to let the users write a method returning a boolean in a safe way so they do not inject malicious code in the page and alter the dom nor steal info of the rest of the components in the page.

function( valuesToUse ) {

  //userprovided logic returning true or false depending on the input
  return valuesToUse.favouriteAnimal === "Lizard"
}

Answer

As long as users only run their own code, there’s no need for any security measures. If they break the site, they break it only for themselves.

If these codes are going to be shared, the only reliable way is to have an sandboxed IFRAME and run everything in there (look at how SO snippets, JS fiddle and similar sites work). In this case, user scripts won’t be able to interact with the main page though. Here’s a good article on the topic: https://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

If you need userscripts that 1) can interact with the main page AND 2) can be shared between users, then you have to invent your own programming language and compile it to javascript on the fly. There’s no option in JS to sandbox the built-in eval.



Source: stackoverflow