<iframe src="/preview/123" sandbox></iframe>
<iframe src="/preview/123" sandbox="allow-scripts"></iframe>
<iframe src="/preview/123" sandbox="allow-scripts allow-same-origin"></iframe> <!-- careful -->
An empty sandbox attribute turns on every restriction for the framed page:
- no scripts
- no form submissions
- no popups
- no navigation of the top window
- a unique, opaque origin, so it can't read cookies or storage, even if it comes from your own domain
Each token switches one restriction off again, for example allow-scripts, allow-forms, allow-popups and allow-same-origin.
Why the pair is dangerous: say the framed page is on the same origin as the parent, and you give it both allow-scripts and allow-same-origin. Its script now runs with your origin. It can reach into the parent page, remove the sandbox attribute from its own iframe, and reload itself with no sandbox at all. MDN warns about exactly this.
Good uses:
- previews of user-written HTML
- ads and third-party widgets
For untrusted content, serve it from a separate domain as well, such as a usercontent domain. Then even allow-same-origin only gives it that other origin.
Don't confuse sandbox with the allow attribute. allow controls features like the camera through Permissions Policy.
- An empty
sandboxblocks scripts, forms, popups and top navigation. - An empty
sandboxalso gives the frame a unique, opaque origin. - Tokens like
allow-scriptsswitch single restrictions back off. - Same-origin content with both
allow-scriptsandallow-same-origincan remove its own sandbox. - Serve untrusted content from a separate domain as an extra layer.