[英]javascript, js - Access a js function inside an iframe from the parent window
Good day to all. 大家好日子。
I have the following setup: 我有以下设置:
A page with html, js, etc. (usual stuff) and an iFrame. 一个包含html,js等的页面(通常的东西)和一个iFrame。 In the iFrame I have a function that do something (anything.. alert('test'); for example). 在iFrame中,我有一个执行某些操作的功能(任何事情..警报('test');例如)。
I need to run that function if I click on a button on the main page. 如果我点击主页面上的按钮,我需要运行该功能。
For example if I push button alert in the main page, in the iFrame must appear an alert with the 'test' word. 例如,如果我在主页面中按下按钮警报,则iFrame中必须出现带有“测试”字样的警报。
document.frames[n]
make frames accessible by the order they appear in the document. document.frames[n]
使框架可以按文档中出现的顺序访问。 so document.frames[0].contentWindow.myFunction()
would call your function inside the frame in case the iframe is the only frame. 所以document.frames[0].contentWindow.myFunction()
会在框架内调用你的函数,以防iframe是唯一的框架。
Calling a function in the main window from the frame works via top
like top.myFunction()
. 从框架中调用主窗口中的函数通过top
工作,如top.myFunction()
。 If you just want to go one level up you use parent
. 如果你只想提高一级,你就使用parent
级。
For even more robustness: 为了更加健壮:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and 和
...
var el = document.getElementById('targetFrame');
getIframeWindow(el).targetFunction();
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.