Home >Web Front-end >JS Tutorial >How to Call JavaScript Functions in an Iframe from its Parent Page?
Calling JavaScript Functions in an Iframe from the Parent Page
When an iframe is embedded within a webpage, it creates a sandbox environment that isolates the code within it from the parent page. However, there may be scenarios where you need to access and invoke JavaScript functions defined in the iframe from the parent page.
Understanding the Challenge
The standard approach, calling parent.functionName() from within the iframe, does not work in this case. This is because the parent page is not the immediate parent of the iframe, but rather the iframe's sandbox virtual environment.
Accessing the Iframe's Content Window
To access and invoke JavaScript functions within the iframe, you need to obtain a reference to its contentWindow property. This property represents the window object of the iframe, providing you with access to its global variables, functions, and DOM.
Invoking JavaScript Functions
Once you have the contentWindow reference, you can invoke JavaScript functions within the iframe by using the following syntax:
document.getElementById('iframeID').contentWindow.functionName();
where iframeID is the id attribute of the iframe.
Accessing Frames Using window.frames
Alternatively, you can also use window.frames to access your iframe. When using this method, you should note that it might not be supported in all modern browsers. The syntax for this approach is:
window.frames[0].frameElement.contentWindow.functionName();
Example
Suppose your iframe has an id of "targetFrame" and the function you want to invoke is called "targetFunction()":
document.getElementById('targetFrame').contentWindow.targetFunction();
The above is the detailed content of How to Call JavaScript Functions in an Iframe from its Parent Page?. For more information, please follow other related articles on the PHP Chinese website!