The HTML sandbox attribute is a security feature used to apply additional restrictions to content embedded in the <iframe> element.
Definition and Usage
➔ This is essentially a security measure designed to prevent potentially malicious activities from affecting key documents or user data.
➔ When the sandbox attribute is present in the <iframe> tag, the browser applies the highest level of restrictions by default.
➔ It is possible to selectively lift restrictions by providing a space-separated list of values.
➔ The following actions are blocked by default with an empty sandbox attribute:
- Script execution is disabled.
- Form submission block.
- Plugins loading block.
- APIs block.
- Links opening in a new tab or window block.
- Preventing access to cookies or other storage mechanisms.
- Automatically triggered features block.
➔ It is possible to specify one or more of the following values to re-enable specific functionality:
- allow-forms: Enable form submission.
- allow-scripts: Enable scripts.
- allow-same-origin: Enable same origin.
- allow-popups: Enable popups.
- allow-popups-to-escape-sandbox: Enable popups to new window.
- allow-top-navigation: Enable navigate to parent page.
- allow-pointer-lock: Enable Api.
- allow-modals: Enable opening modal window.
Syntax
//In HTML
Example: <iframe src="for_untrusted_content.html" sandbox></iframe>
Example: <iframe src="for_trusted_content.html" sandbox="allow-scripts allow-forms"></iframe>
//In JaveScript
const element = document.getElementById('myIframe');
element.setAttribute('sandbox', 'allow-scripts allow-forms');
//OR
// Set as a string value (overwrites existing values)
element.sandbox = 'allow-scripts allow-forms';
// Alternatively, (adds to existing values)
element.sandbox.add('allow-scripts');
element.sandbox.add('allow-forms');
// To remove a flag
element.sandbox.remove('allow-top-navigation');
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML sandbox attribute example</title>
</head>
<body>
<h3>HTML sandbox attribute example</h3>
<p>Set the src correctly to load the source (use your own api) and remove sandbox to show content.</p>
<!-- "https://www.openstreetmap.org/export/embed.html?bbox=0.0%2C60.0%2C00.0%2C00.0&layer=mapnik" -->
<iframe sandbox id="sample" title="sandbox Example" width="450" height="200" src="resource-path">
</iframe>
</body>
</html>
Click on the "Try it Now" button to see how it works.