简体   繁体   English

在位于iframe中的.js文件中调用javascript函数

[英]calling a javascript function inside a .js file which resides in a iframe

i have a default.aspx page which contains a iframe, whose source is set to a default.htm page. 我有一个default.aspx页面,其中包含一个iframe,其源设置为default.htm页面。 The default.htm in turn has a link to a script file(). default.htm依次具有指向脚本file()的链接。 Is it possible to access the functions in the script file in my default.aspx page ?if so how ?? 是否可以在default.aspx页面中访问脚本文件中的功能?

Yes, if the page in the iframe was loaded from the same domain as the page containing the iframe (this is the same-origin policy). 是的,如果iframe中的页面是从与包含iframe的页面相同的域加载的(这是同源策略)。

Note that the iframe and containing page both have a global 'window' object, but they are different. 请注意,iframe和包含页面都具有全局“窗口”对象,但是它们是不同的。

To access variables and functions from scripts in the inner frame from the outer page, you'd need to be able to reference the iframe as an object. 要从外部页面的内部框架中的脚本访问变量和函数,您需要能够将iframe作为对象引用。 For example, if it's the only iframe on the page, you could just prepend window.frames[0]. 例如,如果它是页面上唯一的iframe,则只需在window.frames[0]. to any variable name and you'll be referring to the one declared by the scripts in the iframe. 任何变量名,您将引用iframe中脚本声明的变量名。 If it's not, then you may have to locate the iframe using an ID: 如果不是,则可能必须使用ID定位iframe:

var iframewindow = document.getElementById('myframe').contentWindow;
// read the content of the 'myvar' variable which was set within that frame.
alert(iframewindow.myvar);

To access the outer page's variables and functions from the inner page, you'd prepend window.parent. 要从内页访问外页的变量和函数,请在window.parent. to the start of them. 到他们的开始。

Assuming that default.htm is on the same domain as default.aspx, you can use the following javascript to call functions in default.htm: 假设default.htm与default.aspx在同一域中,则可以使用以下JavaScript调用default.htm中的函数:

var myIframe = document.getElementById("iframe_id").contentWindow;
myIframe.func1();
myIframe.func2();
myIframe.func3();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM