如何使用JavaScript修改iframe的sandbox属性?问题求助
问题原因
当iframe完成加载后,再通过setAttribute修改sandbox属性是无效的——浏览器只会在iframe初始化加载阶段读取并应用sandbox的限制规则,加载完成后修改属性不会触发规则重新生效。你的代码里hello()绑定在body onload事件执行,此时iframe已经加载完毕,所以修改sandbox不会起作用。
解决方案
方案1:在iframe加载前修改sandbox属性
把脚本放在iframe标签之前,或者使用DOMContentLoaded事件(DOM解析完成但资源未加载时触发),确保在iframe开始加载前修改属性:
<!DOCTYPE html> <html> <head> <script> document.addEventListener('DOMContentLoaded', function() { const iframes = document.getElementsByTagName('iframe'); for (var i = 0; i < iframes.length; i++) { iframes[i].setAttribute('sandbox', 'allow-forms'); } }); </script> </head> <body> <h1>The iframe sandbox attribute</h1> <iframe id='ikea' src="demo_iframe_sandbox_form.htm" sandbox=""> <p>Your browser does not support iframes.</p> </iframe> <p>The "Submit" button will submit the form in the inline frame.</p> <p>Since the sandbox attribute is set to an empty string (""), the submission of the form in the inline frame will be blocked.</p> <p>Add "allow-forms" to the sandbox attribute, to allow form submission.</p> </body> </html>
方案2:重新创建iframe替换原有的
如果必须在iframe加载后修改规则,可以删除原iframe,创建一个新的iframe并设置好sandbox属性,再插入到原来的位置:
<!DOCTYPE html> <html> <body onload="hello()"> <h1>The iframe sandbox attribute</h1> <iframe id='ikea' src="demo_iframe_sandbox_form.htm" sandbox=""> <p>Your browser does not support iframes.</p> </iframe> <p>The "Submit" button will submit the form in the inline frame.</p> <p>Since the sandbox attribute is set to an empty string (""), the submission of the form in the inline frame will be blocked.</p> <p>Add "allow-forms" to the sandbox attribute, to allow form submission.</p> <script> function hello(){ const iframe = document.getElementById('ikea'); // 保存原有属性 const src = iframe.src; const parent = iframe.parentNode; // 删除原iframe iframe.remove(); // 创建新iframe const newIframe = document.createElement('iframe'); newIframe.id = 'ikea'; newIframe.src = src; newIframe.sandbox = 'allow-forms'; // 插入到原位置 parent.appendChild(newIframe); } </script> </body> </html>
内容的提问来源于stack exchange,提问作者Manoj Tudu
相关产品推荐
相关产品推荐

