The sandbox Attribute
You have met sandbox briefly in earlier lessons. This one is the full story. The sandbox attribute puts an iframe in a locked room: by default the embedded page can do almost nothing, and you unlock only the specific powers it needs. It is one of the strongest tools HTML gives you, and it is only one attribute.
What You Will Learnβ
- What an empty
sandboxtakes away - What each permission token adds back
- The
allow-scriptsplusallow-same-origintrap - How to choose the smallest set of permissions
- Where sandbox does and does not help
- How to apply a sandbox with a header
The Big Ideaβ
Most security settings say what to block. sandbox flips this: everything is blocked until you allow it. That is called a deny-by-default design, and it is why sandbox is safer than lists of rules you might forget to update.
- The Code
- Permission Lab
- Scenario Picker
<!-- Everything blocked -->
<iframe src="preview.html" title="Preview" sandbox></iframe>
<!-- Only scripts allowed -->
<iframe src="https://widgets.example.net/calc" title="Calculator"
sandbox="allow-scripts"></iframe>
<!-- Several permissions, space separated -->
<iframe src="https://pay.example.net/form" title="Payment"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"></iframe>
<iframe src="https://widgets.example.net/page" title="Widget" sandbox></iframe>| What the embedded page can do | Status |
|---|---|
| Run JavaScript | Blocked |
| Keep its real origin (its own cookies and storage) | Blocked |
| Submit forms | Blocked |
| Open popups and new tabs | Blocked |
| Show alert, confirm and prompt boxes | Blocked |
| Send the whole page to another address | Blocked |
| Start downloads | Blocked |
| Lock the mouse pointer | Blocked |
- Good: No warnings. This is a tight set of permissions.
A simplified model of the main permissions. Green "Blocked" means a power the embed does not have. Real browsers have a few more tokens and details, listed in the MDN documentation.
Scenario 1 of 5: A preview of a static HTML page a visitor wrote, served from your own domain
What an Empty sandbox Doesβ
Adding the bare attribute sandbox (or sandbox="") applies all restrictions. The embedded page:
- cannot run JavaScript,
- cannot submit forms,
- cannot open popups or new tabs,
- cannot show
alertand similar boxes, - cannot navigate your whole page to another address,
- cannot start downloads,
- cannot use plugins, or lock the pointer,
- and is treated as coming from a unique, empty origin, so it cannot use its own cookies or
localStorage, and cannot be treated as the same site as anything else.
It can still show HTML and CSS, load images, and play media. That is why an empty sandbox suits previews and static content.
The Permission Tokensβ
You add powers back with space-separated tokens. Unknown tokens are ignored, so a typo silently does nothing. Always test.
| Token | What it allows | Think twice when |
|---|---|---|
allow-scripts | Running JavaScript | Combined with allow-same-origin (see below) |
allow-same-origin | Keeping its real origin, so its own cookies and storage work | Content is from your own site |
allow-forms | Submitting forms | The page could show a fake form |
allow-popups | window.open and links with target="_blank" | The popups are not trusted |
allow-popups-to-escape-sandbox | Popups open without the sandbox | Almost always; use only for trusted providers |
allow-modals | alert, confirm, prompt | They can be used to annoy or mislead |
allow-top-navigation | Navigating the whole page | Nearly always; it enables page hijacking |
allow-top-navigation-by-user-activation | The same, but only right after a click | A safer choice if you need top navigation |
allow-downloads | Starting downloads | The source is unknown |
allow-pointer-lock | Locking the pointer (games and 3D) | Rarely needed |
Browsers add new tokens from time to time. The list on MDN is the complete, current reference.
Same origin, and an empty originβ
The word "origin" comes from HTML Security Basics: scheme, host, and port. Without allow-same-origin, the framed page gets an opaque origin that matches nothing, so:
- it cannot read its own cookies or
localStorage, and many apps break, - requests from it to its own server count as cross-origin,
- and, importantly, if it is your content, it is also cut off from your site's origin.
For a page from another site, adding allow-same-origin returns that site's origin to it, not yours. It still cannot touch your page. That is why it is a common, reasonable choice for video and payment widgets.
The Trap: allow-scripts Plus allow-same-originβ
If the framed page comes from your own origin, and you add both allow-scripts and allow-same-origin, the page's script can reach its own iframe element in the parent, delete the sandbox attribute, and reload itself with no restrictions. The sandbox then protects nothing.
<!-- Same-origin content: do not do this -->
<iframe src="/uploads/page.html" sandbox="allow-scripts allow-same-origin"></iframe>
What to do instead:
- Remove
allow-same-originif the content only needs to run scripts. - Serve untrusted content from a separate domain, so even its "real origin" cannot touch your site. This is how many code-playground and user-content platforms work.
- Check the Permission Lab: tick both tokens and switch between "my own site" and another site to see the warning change.
Choosing the Smallest Setβ
- Start with an empty
sandbox. - Load the page and read the Console. Browsers report blocked actions, such as "Blocked script execution" or "Blocked a frame from submitting a form".
- Add one token that fixes a real, needed feature.
- Repeat until the embed works. Stop there.
- Document why each token is there, with a short comment in your template.
The Scenario Picker tab gives you five realistic embeds to practise this.
Sandbox and the allow Attributeβ
These are separate controls that work together:
| Attribute | Controls |
|---|---|
sandbox | Broad page behaviours: scripts, forms, popups, navigation, origin |
allow | Browser features: camera, microphone, geolocation, fullscreen, payment |
A sandboxed frame can still be refused a feature that allow does not grant. Use both. Features are also controlled by Permissions-Policy headers, as covered in iFrame Security.
Sandbox as a Headerβ
The same idea exists as a Content Security Policy directive, set by a server. It applies to any page it is sent with, even when that page is not in a frame:
Content-Security-Policy: sandbox allow-scripts
This is useful for files that visitors upload, such as HTML or SVG. If the response carries this header, opening the file directly in a browser tab gets the same restrictions as a sandboxed frame. See Content Security Policy.
Where Sandbox Helps, and Where It Does Notβ
| It helps against | It does not |
|---|---|
| Untrusted or third-party pages running scripts | Stop a page from showing misleading content inside its rectangle |
| Frames submitting forms or opening popups | Replace escaping and sanitising visitor input (see XSS Basics) |
| Frames hijacking the whole page | Hide the visitor's address from the embedded host (see referrerpolicy) |
| Uploaded files being opened as full pages (header form) | Protect a page that is not in a frame, unless the CSP header is used |
| Embedded code reaching your origin | Work in browsers too old to support it (very rare today) |
Sandbox settings apply when the frame loads a page. If you change the sandbox attribute with JavaScript afterwards, the new setting takes effect only the next time the frame navigates, not instantly. Set it in the HTML, before the frame loads.
A Note on srcdocβ
An iframe with srcdoc takes its HTML from the attribute instead of loading a URL. With allow-same-origin, a srcdoc page gets your origin, which is dangerous if the HTML is untrusted. Without allow-same-origin, it gets an empty origin. Combine srcdoc with sandbox, and never add allow-same-origin for untrusted content.
Checking Your Setupβ
- Open DevTools and the Console. Look for lines that begin "Blocked" or "Ignored", which show what the sandbox stopped. A typo in a token name may appear as an unrecognised value.
- Open Elements, and check that each third-party frame has a
sandboxattribute. Hover it to see the exact string. - Test every feature of the embed: playing, paying, logging in, resizing.
- For same-origin content, search your code for
allow-scripts allow-same-origintogether.
Best Practicesβ
- Sandbox every third-party and visitor-supplied frame.
- Start empty, then add one token at a time.
- Never combine
allow-scriptsandallow-same-originfor content from your own origin. - Avoid
allow-top-navigation. If you need it, use the by-user-activation version. - Avoid
allow-popups-to-escape-sandboxunless a trusted provider requires it. - Serve untrusted content from a separate domain.
- Use
allowandPermissions-Policyfor browser features. - Follow each provider's documentation, and test after each provider update.
- Keep a short comment explaining each permission.
Quick Checklistβ
- Every third-party frame has a
sandbox - Each token is there for a reason you can state
- No frame from your origin has
allow-scriptsandallow-same-origintogether - No
allow-top-navigationunless it is truly needed - Untrusted content is on a separate domain
- The Console shows no unexpected blocked actions
- Uploaded HTML and SVG are served with a
sandboxCSP header, or from another domain
Security and Privacy Notesβ
- Sandbox limits actions, not what the embedded host learns. The host still receives the request, the visitor's IP address, and a referrer unless you control that. Use
referrerpolicyand click to load, as in iFrame Security. - An empty origin can break consent and login tools that rely on cookies. If an embed needs storage, you must grant
allow-same-origin, and accept that trade-off. - Do not treat sandbox as the only layer. Keep browsers updated, and combine it with CSP and careful input handling.
- Test with permission. Try these settings on your own pages and test pages, not other people's sites.
Global Audience Notesβ
- Payment and identity providers vary by country. Check each provider's current documentation for the sandbox set it supports, as these change.
- Sandboxed embeds fail quietly. Visitors on a weak connection see an empty box. Offer a link to open the content in a new tab, and write a clear
titlein the page's language. - Older and uncommon browsers may not support newer tokens. The embed should degrade to a link, not break the page.
Common Mistakes to Avoidβ
- Leaving out
sandboxon a third-party frame. - Adding every token "just in case".
- Combining
allow-scriptsandallow-same-originon your own content. - Mistyping a token, so it is silently ignored.
- Using
allow-top-navigationfor convenience. - Assuming sandbox hides the visitor's information from the embedded host.
- Changing
sandboxwith JavaScript and expecting an instant effect. - Giving
srcdoccontentallow-same-originwhen it holds untrusted HTML. - Forgetting
allowfor camera, microphone, or fullscreen features. - Never re-testing after a provider changes its embed.
Practice Timeβ
- In the Permission Lab, turn off the sandbox. Which warning appears?
- Turn it back on with nothing ticked. Which row, if any, is not "Blocked"?
- Tick
allow-scriptsandallow-same-origin. Switch between your own site and another site. How does the warning change? - Tick
allow-top-navigation, then swap it for the by-user-activation token. What changes in the table? - Complete all five scenarios in the Scenario Picker.
- Add a sandboxed frame to a test page, then open the Console to see which actions are blocked.
- Write the CSP header you would send with a folder of visitor-uploaded HTML files.
- Bonus: find every
iframeon one of your own pages, and write down what each token is for.
Quick Recapβ
Click a question to check your answer.
1. What does an empty sandbox do?
It blocks scripts, forms, popups, modals, top navigation, downloads, and plugins, and gives the page an empty origin.
2. How do you allow a specific power?
Add a token such as allow-scripts or allow-forms to the sandbox value, separated by spaces.
3. Why is allow-scripts plus allow-same-origin dangerous?
On content from your own origin, the page's script can remove its own sandbox attribute, so the sandbox is useless. For another site's content, it only gives that site its own origin back.
4. How do you choose permissions?
Start with an empty sandbox, read the Console's blocked messages, add one token for each needed feature, and stop when the embed works.
5. What is the difference between sandbox and allow?
sandbox controls broad page behaviours such as scripts, forms and navigation. allow controls browser features such as camera, microphone and fullscreen.
6. How can a server apply a sandbox?
With the Content-Security-Policy: sandbox ... header, which also protects uploaded files opened directly in a browser.
Key Takeawaysβ
sandboxis deny by default. Add back only what is needed.- An empty origin means no cookies or storage until
allow-same-originis added. - Never pair
allow-scriptswithallow-same-originfor your own content. - Avoid
allow-top-navigationandallow-popups-to-escape-sandbox. - Sandbox plus
allow, CSP, andreferrerpolicywork as layers. - Test in the Console, and re-test when providers change.
Next up: noreferrer, where you will learn what a link tells the next site about where the visitor came from, and how to control it.