Disable JavaScript in an <iframe>
by setting the sandbox
attribute
I was loading a web page in an iframe, and I wanted to make sure it couldn’t run any JavaScript.
I found the sandbox
attribute on the <iframe>
element, which lets you control what can happen within the iframe – for example, whether it can run scripts or control forms. By default, you can do quite a lot of stuff inside an iframe, but setting sandbox=""
will disable all of it.
Here’s an example we can use:
<iframe srcdoc="
<script>
window.addEventListener('DOMContentLoaded', function() {
document.querySelector('main').innerText = 'This iframe has JavaScript!';
});
</script>
<noscript>This iframe doesn't have JavaScript!</noscript>
<main></main>"></iframe>
And let’s load this with and without the sandbox
attribute:
<iframe>
<iframe sandbox="">