I have a page with an iframe. Inside that iframe I have a javascript function like this:
function putme() {}
How can I call this function on the main page?
Definition and Usage. The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.
Set the iframe to the appropriate width and height and set the scrolling attribute to "no". If the area you want is not in the top-left portion of the page, you can scroll the content to the appropriate area.
To get the element in an iframe, first we need access the <iframe> element inside the JavaScript using the document. getElementById() method by passing iframe id as an argument. const iframe = document.
window.frames['frameName'].putme();
Do note that this usually only works if the iframe is referring to a page on the same domain. Browsers restrict access to pages within frames that belong to a different domain for security reasons.
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');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.putme();
...
}
...
If the iframe is in a different domain than the outer page, with great difficulty, or not at all.
In general, the browser prevents javascript from accessing code from a different domain, but if you control both pages, there are some hacks to make something work. More or less.
For example, you can change the fragment of the URL of the iFrame from the outer one, poll the fragment from inside the iframe and call that function. There is a similar trick with the name of the window.
On the frameset, specify a name for your frame and in main page you can access the frame by its given name:
window.[FrameName].putme();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With