从Javascript中的其他框架访问框架元素

问题描述:

如何从其他框架访问框架元素。对于防爆:从Javascript中的其他框架访问框架元素

main.html中:

<html> 
    <head> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </head> 
    <frameset rows="33%,33%,*"> 
     <frame class="fra" src="frame1.html"/> 
     <frame class="fra" src="frame2.html"/> 
    </frameset> 
</html> 

frame1.html:

<html> 
    <HEAD> 
     <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS" /> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </HEAD> 
    <body> 
     <b><p id="para"> This is frame one.html </p></b> 
    </body> 
</html> 

frame2.html:

<html> 
    <HEAD> 
     <meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS" /> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    </HEAD> 
    <body> 
     <b><p id="para"> This is frame two.html </p></b> 
     <button id="but"> Get data </button> 
     <script> 
      $(document).ready(function(){ 
       $("#but").click(function(){ 
        alert(window.frames[0].document.getElementById('para')); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

一旦按钮从帧2点击然后我需要获取frame1中存在的“para”id元素的数据。所以,我试图访问下面显示的 元素。但它没有奏效。

window.frames[0].document.getElementById('para') 

它显示的错误为:

Uncaught TypeError: Cannot read property 'document' of undefined

所以,window.frames[0]本身不确定 。可任何一个可以帮助我解决这个问题?

+0

由于安全使用父母访问父母然后其他框架的浏览器将阻止的行动, 看到这个[答案](http://*.com/questions/25098021/securityerror-blocked-a-frame-with -origin-from-access-a-cross-origin-frame) –

+0

[SecurityError:Blocked a frame with origin from access from a cross-origin-frame](http://msdn.microsoft.com/zh-cn/library/system.aspx?displaylang=zh-cn&id=25098021/securityerror-阻塞的一帧与 - 原点从 - 访问-A-跨来源帧) –

您应该在您的iframe上放置id,例如“iframe1”和“iframe2”。

<frame class="fra" src="frame1.html" id="frame1" /> 
    <frame class="fra" src="frame2.html" id="frame2" /> 

然后:

$(window.parent.document).find("#iframe1").contents().find("#para") 

应该给你从iframe2在框架中的一个访问元素ID为 “段”。 $(window.parent.document)将允许您从iframe2返回到主文档,然后查找iframe1,然后通过contents()将允许您进入iframe1,您将可以在其中找到“#iframe2”段“元素。