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. In the iFrame I have a function that do something (anything.. alert('test'); for example).
I need t开发者_StackOverflowo 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.
document.frames[n]
make frames accessible by the order they appear in the document.
so document.frames[0].contentWindow.myFunction()
would call your function inside the frame in case the iframe is the only frame.
Calling a function in the main window from the frame works via top
like top.myFunction()
. If you just want to go one level up you use 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();
...
精彩评论