乐闻世界logo
搜索文章和话题

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

1个答案

1

In web development, it is often necessary to handle or manipulate an iframe created by the parent window within the parent window. To access the iframe window object from the parent window's JavaScript code, follow these steps:

  1. Ensure the iframe has fully loaded its content: Before accessing the iframe's content or functionality, verify that the iframe has completed loading. This can be done by listening for the iframe's load event.

  2. Use the contentWindow property to obtain a reference: Access the iframe's window object by retrieving the contentWindow property of the iframe element. This property provides a reference to the window object of the iframe's content.

Here is a specific example demonstrating how to obtain a reference to the window object of an iframe created by the parent window and invoke a method inside the iframe after it has loaded:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Parent Window</title> </head> <body> <iframe id="myIframe" src="iframe.html" onload="iframeLoaded()"></iframe> <script> function iframeLoaded() { var iframeWindow = document.getElementById('myIframe').contentWindow; // Now you can access the window object of the iframe iframeWindow.someFunctionInsideIframe(); // Assuming the iframe has a function named someFunctionInsideIframe } </script> </body> </html>

In this example, we create an iframe element and attach an onload event handler function named iframeLoaded. Once the iframe has loaded, the iframeLoaded function executes. Within this function, we obtain the iframe's window object via the contentWindow property of the iframe element and call the method someFunctionInsideIframe defined inside the iframe.

Note that if the iframe and parent window are not same-origin (i.e., the protocol, domain, or port differs), the browser's same-origin policy will prevent the parent window from accessing the iframe's content. In such cases, attempting to access the contentWindow property will result in a security error.

2024年8月13日 10:48 回复

你的答案