2015-09-07 72 views
0

我想获取iframe的内容,但发生错误。我想获取iframe的内容,但发生错误

错误:权限被拒绝访问属性 '文件'

... irstChild)},内容:函数(){返回m.nodeName(一, “IFRAME”)a.contentDocument ...?

我的代码:

<iframe frameborder="0" scrolling="no" width="130" height="198" 
    src="https://tpc.googlesyndication.com/simgad/9598136166282506848" name="imgbox" class="iView"> 
    <p>iframes are not supported by your browser.</p> 
</iframe> 


$(document).ready(function(){ 
    var cnt = $(".iView").contents(); 
    console.log(cnt); 
    }) 
+0

好像你是在iFrame内部打开第三方网站并试图访问它的文档。你不能那样做。 – vijayP

+0

有什么办法可以获得iframe的内容? – Zisu

+0

如果iFrame具有指向存在于您自己的域中的Web资源的'src',即主父页面的域,那么您可以访问其内容。 – vijayP

回答

1

同源策略限制您在iframe内容访问DOM。但是,它并不妨碍您几乎不会嵌入页面。

有关同源策略的更多详细信息,以及如何解决它,请参阅下面的社区维基:Ways to circumvent the same-origin policy

0

通过JavaScript如果是从同一台服务器可以访问的iFrame内容。否则它不会允许您访问iFrame内容。 错误:权限被拒绝访问属性“文档”。

0

实际上,当您从跨域进行此操作时,无法完成此操作。您将获得权限被拒绝的错误。当Iframe源来自同一台服务器时,只能这样做。

0

我创建了一个示例代码。现在你可以很容易从不同的领域了解你不能访问iframe的内容..我们可以访问iframe内容的相同域名

我与你分享我的代码,请运行此代码检查控制台。我在控制台打印图像src。有四个iframe中,两名来自iframe的同一域&另外两个即将从其他域(第三方)。你可以在控制台中看到两个影像SRC(https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif

https://www.google.com/logos/doodles/2015/arbor-day-2015-brazil-5154560611975168-hp2x.gif),还可以看到两个权限错误(2错误:权限被拒绝访问属性 '文件'

... irstChild)},内容:函数(){返回m.nodeName(一, “IFRAME”)a.contentDocument ......

)来自第三方iframe。

<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> 
<p>iframe from same domain</p> 
    <iframe frameborder="0" scrolling="no" width="500" height="500" 
    src="iframe.html" name="imgbox" class="iView"> 

</iframe> 
<p>iframe from same domain</p> 
<iframe frameborder="0" scrolling="no" width="500" height="500" 
    src="iframe2.html" name="imgbox" class="iView1"> 

</iframe> 
<p>iframe from different domain</p> 
<iframe frameborder="0" scrolling="no" width="500" height="500" 
    src="https://www.google.com/logos/doodles/2015/googles-new-logo-5078286822539264.3-hp2x.gif" name="imgbox" class="iView2"> 

</iframe> 

<p>iframe from different domain</p> 
<iframe frameborder="0" scrolling="no" width="500" height="500" 
    src="http://d1rmo5dfr7fx8e.cloudfront.net/" name="imgbox" class="iView3"> 

</iframe> 

<script type='text/javascript'> 


$(document).ready(function(){ 
    setTimeout(function(){ 


     var src = $('.iView').contents().find(".shrinkToFit").attr('src'); 
    console.log(src); 
     }, 2000); 


    setTimeout(function(){ 


     var src = $('.iView1').contents().find(".shrinkToFit").attr('src'); 
    console.log(src); 
     }, 3000); 


    setTimeout(function(){ 


     var src = $('.iView2').contents().find(".shrinkToFit").attr('src'); 
    console.log(src); 
     }, 3000); 

     setTimeout(function(){ 


     var src = $('.iView3').contents().find("img").attr('src'); 
    console.log(src); 
     }, 3000); 


    }) 


</script> 
</body>