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

Calling a parent window function from an iframe

1个答案

1

In web development, an iframe (inline frame) is commonly used to embed another document within the current page. To call JavaScript functions in the parent window from an iframe, you can use the parent keyword, which refers to the parent window hosting the iframe. However, it's important to note that due to security considerations (same-origin policy), this operation is only possible when the parent window and the content within the iframe are from the same origin (i.e., the protocol, domain, and port are identical).

Here is an example of calling a parent window function from an iframe:

First, assume you define a function on the parent window:

html
<!-- Parent page index.html --> <!DOCTYPE html> <html> <head> <title>Parent Page</title> <script> function parentFunction() { alert('This is a function from the parent window!'); } </script> </head> <body> <iframe src="iframe.html" width="300" height="200"></iframe> </body> </html>

Then, on the iframe page, you can call this function:

html
<!-- iframe page iframe.html --> <!DOCTYPE html> <html> <head> <title>iframe Page</title> <script> function callParentFunction() { parent.parentFunction(); } </script> </head> <body> <button onclick="callParentFunction()">Call Parent Window Function</button> </body> </html>

In this example, when the user clicks the button on the iframe page, it will call the parentFunction defined on the parent window, displaying an alert popup.

It's important to note that in practice, due to browser security policies, cross-origin restrictions may apply, and performing such operations between different domains may result in security errors. To safely communicate between an iframe and the parent window across different domains, you can use the window.postMessage method.

2024年6月29日 12:07 回复

你的答案