Question

I've been reading up on HTML5's sandbox attribute for <iframe>s. According to the documentation the sandbox attribute allows a developer to selectively restrict what actions can be done in an <iframe>. Is the sandbox attribute purely a security measure? Does the sandbox attribute enable web designers to implement any new functionality and if so can anyone point to any examples?

Was it helpful?

Solution

Well, it is purely a security feature, but it does allow new functionality as well. Take for example embedding third party (user) content (e.g. HTML files). Traditionally you would need to set up a separate domain from which you would serve that content, now however you can simply serve it from wherever you want to and have it treated as if it's from a separate domain.

On top of that it can prevent this third party content from doing certain things, which you could not have prevented previously like:

  • allow-top-navigation: Preventing it from breaking out
  • allow-pointer-lock: Preventing it from taking the cursor hostage
  • allow-popups: Preventing it from breaking out through popups
  • allow-scripts: Simply blocking all scripts (could also have been done through CSP)

Realistically the combination of the sandbox attribute combined with controlled CSP headers gives an incredible amount of control to run third party code in a safe environment. It's not 100% there yet, but we're getting quite close.

OTHER TIPS

The sandbox can actually be pretty handy in testing. Consider the following:

tester.html

<script> document.cookie='foo=bar' </script>
<iframe src=testee.html>

testee.html

<script> console.log(document.cookie) </script>

When loading tester.html you will see on the console "foo=bar" which was dumped by testee.html.

Now add to the iframe the sandbox attribute and the cookie is gone - the sandbox created a separate runtime environment for testee.html, where it doesn't get cookie pollution from other pages that were/are open in the browser during the development process. So when you need a sterile test bed but can't or don't want to clear the browser cache, here's a quick and simple solution.

The sandbox attribute does not enable any extra functionality, it only restricts the functionality of the iframe. The only reason to use it is as a security measure.

The iframe sandbox is purely a security feature. A good resource is always the W3 HTML5 specification.

When the attribute is set, the content is treated as being from a unique origin, forms, scripts, and various potentially annoying APIs are disabled, links are prevented from targeting other browsing contexts, and plugins are secured.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top