How to Call parent Javascript function from inside an iframe
In web development, it is often necessary to call JavaScript functions located on the parent page from within an iframe. This requirement can be addressed through several methods, but it is important to note that for security reasons, most modern browsers impose strict restrictions on cross-origin scripts. If the iframe and parent page are not same-origin (i.e., the protocol, domain, and port are not identical), these methods may not apply.Methods Under the Same-Origin PolicyIf the iframe and parent page are same-origin, you can use the keyword to call JavaScript functions on the parent page. Here is an example:Assume the parent page (parent.html) contains a function called :The child page (child.html) needs to call this function:In this example, when you click the button on the child page, it calls the function to invoke the function defined on the parent page, and displays an alert dialog containing the message.Methods Under Cross-Origin PolicyIf the iframe and parent page are not same-origin, more complex methods such as are required to securely communicate. This method allows cross-origin communication but requires additional event listeners and message validation on both pages to ensure security.In this cross-origin example, the child page sends a message to the parent page using , and the parent page listens for the event, executing the corresponding function after verifying the message source is trusted.ConclusionThe choice of method depends on your specific requirements, especially considering security and cross-origin issues. For same-origin pages, using the object is a straightforward approach. For scenarios requiring cross-origin communication, provides a secure and flexible solution.