To call JavaScript functions in the parent window from an iframe, you can typically use the parent keyword. The parent keyword references the parent window hosting the iframe. However, due to the browser's same-origin policy, seamless JavaScript invocation is only possible when the parent window and the iframe share the same domain.
Suppose we have a function parentFunction defined in the parent window, and we want to call it from the child window (i.e., within the iframe). The parent window's code might look like this:
html<!DOCTYPE html> <html> <head> <title>Parent Window</title> <script> function parentFunction() { alert('This is a function in the parent window!'); } </script> </head> <body> <iframe src="iframe.html" id="myIframe" ></iframe> </body> </html>
Within the iframe, you can call the parent window's parentFunction as follows:
html<!DOCTYPE html> <html> <head> <title>iframe Window</title> <script> function callParentFunction() { parent.parentFunction(); } </script> </head> <body> <button onclick="callParentFunction()">Call Parent Window Function</button> </body> </html>
When the user clicks the button in the iframe, callParentFunction is invoked, which then calls the parent window's parentFunction.
However, if the parent and child windows are on different domains, you will encounter same-origin policy issues, and the browser will block cross-origin script communication. In this case, you can use the window.postMessage method to securely implement cross-origin communication. Here is a simple example using postMessage:
The parent window listens for the message event:
html<!DOCTYPE html> <html> <head> <title>Parent Window</title> <script> window.addEventListener('message', function(event) { // Verify the message origin if (event.origin !== "http://trusted-origin") { return; } // Invoke the function based on message content if (event.data === "callParentFunction") { parentFunction(); } }, false); function parentFunction() { alert('This is a function in the parent window!'); } </script> </head> <body> <iframe src="http://trusted-origin/iframe.html" id="myIframe"></iframe> </body> </html>
The iframe sends a message to the parent window:
html<!DOCTYPE html> <html> <head> <title>iframe Window</title> <script> function callParentFunction() { // Send a message to the parent window parent.postMessage("callParentFunction", "http://parent-origin"); } </script> </head> <body> <button onclick="callParentFunction()">Call Parent Window Function</button> </body> </html>
In this example, postMessage securely passes messages between windows on different domains. The second parameter specifies the message recipient's origin, ensuring only windows from that origin can receive the message. This enables secure communication even between pages from different origins.