Home >Web Front-end >JS Tutorial >How to Call JavaScript Functions in an Iframe from the Parent Page?
Invoking JavaScript Code in an Iframe from the Parent Page
In web development, there are scenarios where you need to interact with JavaScript code embedded within an iframe from the parent page. While it's straightforward to invoke parent functions from an iframe using parent.functionName(), the reverse operation presents a challenge.
Solution
To invoke a function defined within an iframe from the parent page, you can utilize the following code snippet:
document.getElementById('targetFrame').contentWindow.targetFunction();
Replace targetFrame with the id or name of your iframe element.
Another option is to access the frame through the window.frames array:
window.frames[0].frameElement.contentWindow.targetFunction();
Note: The second method may not work in newer versions of Chrome and Firefox due to restrictions on cross-origin communication.
By utilizing these techniques, you can effectively communicate between the parent page and its embedded iframe, enabling you to invoke specific JavaScript functions as needed.
The above is the detailed content of How to Call JavaScript Functions in an Iframe from the Parent Page?. For more information, please follow other related articles on the PHP Chinese website!