开发者

Accessing Javascript Instance from Child iFrame

Can the 开发者_JAVA技巧parent's Javascript variables and functions (essentially the entire runtime instance) be acessed from a child iFrame?

Examples:

**Parent**
<script>function foo()</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script> 

**Child IFrame**
:function bar(){
  alert(foo);
}
$(document).ready(function(){
   $("a").click(function(event){
     alert("Thanks for visiting!");
   });
 });

Questions

1)Can bar() be called from Javascript within the Child frame?

2)Can jquery objects be referenced in the child iFrame when declared in the parent?


The answer is yes but you will need to make additional things to make this work. Basically, an iframe has access to the window object of the parent using window.parent. Therefore a simple way of making bar available to the iframe is

function bar() { alert("foo"); }
window.bar = bar;

In the iframe you can then call:

window.parent.bar();

For objects the same rules apply. Please note that both the main window and iframe must come from the same origin (domain) else browsers will block this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜