Usar el iframe sandbox attribute
El sandbox attribute restricts iframe capabilities, preventing malicious embedded content de accessing el parent página.
- 1
The sandbox attribute on <iframe> applies restrictions to the embedded content. Without sandbox, the iframe can: run scripts, access the parent's DOM (if same-origin), submit forms, load plugins, navigate the parent. With sandbox="" (no values), all restrictions apply. Add specific values to re-enable individual capabilities: allow-scripts, allow-same-origin, allow-forms, allow-popups, etc.
- 2 Minificador HTML →
Minificar the HTML containing iframes to inspect the sandbox attributes. Verify that each iframe has appropriate sandbox restrictions. Never use allow-scripts + allow-same-origin together on untrusted content — this allows the iframe to escape the sandbox and access the parent.
- 3 Escape HTML →
Escapar any user-provided URLs before inserting them into iframe src attributes. This prevents javascript: URL injection. Use a whitelist of allowed URL schemes (https only) and domains. Even with sandbox, a javascript: URL can execute if allow-scripts is present.
Preguntas frecuentes
- What is the most restrictive sandbox?
- sandbox="" (empty string) applies all restrictions: no scripts, no forms, no popups, no same-origin access, no plugins, no navigation. This is the safest. Add only the capabilities the embedded content needs. For a YouTube embed: sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox".
- Why is allow-scripts + allow-same-origin dangerous?
- With both, the iframe can run scripts AND access its own origin as same-origin. If the iframe is same-origin with the parent, it can access the parent's DOM (document.parent), escaping the sandbox entirely. Only use both for trusted same-origin content. For third-party content, use allow-scripts WITHOUT allow-same-origin, or use a different origin (subdomain) for the iframe.