iframe标签sandbox属性对iframe框架的内容启用一些额外的限制条件。可单个条件限制,也可多个条件限制,多个条件限制请用空格隔开。sandbox属性是HTML5的新属性,为了提高iFrame的安全性,可防止不信任的Web页面执行某些操作。
sandbox属性可防止如下操作
访问父页面的DOM(从技术角度来说,这是因为相对于父页面iframe已经成为不同的源了)
执行脚本
通过脚本嵌入自己的表单或是操纵表单
对cookie、本地存储或本地SQL数据库的读写
在iframe框架里允许脚本允许
HTML_target_top.html 按钮脚本代码
<button onclick="echo()">输出:123</button> <div id="dt"></div> <script> function echo() { var d="123"; document.getElementById("dt").innerHTML=d; } </script>
案例代码:
<iframe src="/Template/Test/anli/HTML_target_top.html" sandbox="allow-scripts"></iframe>
在iframe框架里限制所以条件执行
<iframe src="/Template/Test/anli/HTML_target_top.html" sandbox=""></iframe>
在iframe框架里允许提交表单
HTML_phpform.html 文件代码
<form action="/Template/Test/php/form_action.php"> 姓氏:<input type="text" name="xing" value="张"><br> 名字: <input type="text" name="ming" value="三"><br> <input type="submit" value="提交"> </form>
案例代码
<iframe src="/Template/Test/anli/HTML_phpform.html" sandbox="allow-forms"></iframe>
在iframe框架里允许在父窗口打开连接
HTML_target_top.html 代码
<a href="http://www.xuandaima.com/" alt="炫代码" target="_top">炫代码首页</a>
案例代码
<iframe src="/Template/Test/anli/HTML_target_top.html" sandbox="allow-top-navigation"></iframe>
在iframe框架里允许读取xml文件
books.xml 代码
<bookstore> <book category="children"> <title lang="en">php</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="cooking"> <title lang="en">HTML</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="web" cover="paperback"> <title lang="en">XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book> <book category="web"> <title lang="en">mysql</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> </bookstore>
iframe_sandbox_origin.htm代码
<p>图书列表(来自通过 JavaScript 取回的 XML 文件):</p> <script> if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else // for IE 5/6 { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET","/Template/Test/anli/books.xml",false); xhttp.send(); xmlDoc=xhttp.responseXML; x=xmlDoc.getElementsByTagName('title'); for (i=0;i<x.length;i++) { document.write(x[i].childNodes[0].nodeValue); document.write("<br>"); } </script>
案例代码
<iframe src="/Template/Test/anli/iframe_sandbox_origin.html" sandbox="allow-same-origin allow-scripts"></iframe>
注意:sandbox属性使用了允许两个条件,提交名称要以空格隔开 |
<iframe sandbox="条件值"></iframe>
值 | 描述 |
---|---|
"" | 启用所有限制条件 |
allow-same-origin | 允许 iframe 内容被视为与包含文档有相同的来源。 |
allow-top-navigation | 嵌入的页面的上下文可以导航(加载)内容到顶级的浏览上下文环境(browsing context)。如果未使用该关键字,这个操作将不可用。 |
allow-forms | 允许表单提交。 |
allow-scripts | 允许脚本执行。 |