Uncaught DOMException: Blocked a frame with origin "" from accessing a cross-or

iframe跨域访问时,如果访问了被嵌入的界面中的dom信息,则会报错。

案例:

比如:a.html,访问地址为http://test.com/index.html,页面内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <h1 id="parent">父级页面</h1>
    <iframe id="myIframe" src="https://www.baidu.com" height="780"></iframe>
</body>
<script type="text/javascript">
     window.onload = function(){
        var myIframe = document.getElementById("myIframe").contentWindow.document.getElementById("iframeId");
        console.log(myIframe)   
    }
</script>
</html>

此界面中嵌入了iframe,其src为:https://www.baidu.com,父页面index.html在onload事件中,访问了iframe的contentWindow对象中id为iframeId的元素,即使该元素不存在,浏览器也会报告以下错误:

(index):15 Uncaught DOMException: Blocked a frame with origin "http://test.com/index.html" from accessing a cross-origin frame.
    at console.log (<anonymous>)
    at window.onload (http://test.com/index.html/:15:17)

原因是:浏览器不允许跨域访问其它页面中的元素

发布了21 篇原创文章 · 获赞 16 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/thlzjfefe/article/details/105041966