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

如何在 iframe 中调用父窗口 JavaScript 函数

4 个月前提问
3 个月前修改
浏览次数38

1个答案

1

在 iframe 中调用父窗口的 JavaScript 函数通常可以通过使用 parent 关键字来实现。parent 关键字可以引用嵌入了 iframe 的父窗口。不过,由于浏览器的同源策略,只有当父窗口和 iframe 位于同一个域下时,才能够无缝地进行 JavaScript 调用。

假设我们有一个在父窗口定义的函数 parentFunction,我们想要在子窗口(即iframe中)调用这个函数。父窗口的代码可能是这样的:

html
<!DOCTYPE html> <html> <head> <title>父窗口</title> <script> function parentFunction() { alert('这是父窗口的函数!'); } </script> </head> <body> <iframe src="iframe.html" id="myIframe" ></iframe> </body> </html>

在 iframe 中,我们可以这样调用父窗口的 parentFunction

html
<!DOCTYPE html> <html> <head> <title>iframe 窗口</title> <script> function callParentFunction() { parent.parentFunction(); } </script> </head> <body> <button onclick="callParentFunction()">调用父窗口函数</button> </body> </html>

当用户点击 iframe 中的按钮时,callParentFunction 会被调用,该函数进而调用父窗口的 parentFunction

但是,如果父窗口和子窗口不在同一个域下,你会遇到同源策略问题,浏览器会阻止跨域脚本通信。在这种情况下,可以使用 window.postMessage 方法来安全地实现跨域通信。以下是使用 postMessage 方法的一个简单例子:

父窗口监听 message 事件:

html
<!DOCTYPE html> <html> <head> <title>父窗口</title> <script> window.addEventListener('message', function(event) { // 检查消息来源是否可信 if (event.origin !== "http://可信的来源") { return; } // 根据消息内容调用函数 if(event.data === "callParentFunction") { parentFunction(); } }, false); function parentFunction() { alert('这是父窗口的函数!'); } </script> </head> <body> <iframe src="http://可信的来源/iframe.html" id="myIframe"></iframe> </body> </html>

iframe 发送消息给父窗口:

html
<!DOCTYPE html> <html> <head> <title>iframe 窗口</title> <script> function callParentFunction() { // 向父窗口发送消息 parent.postMessage("callParentFunction", "http://父窗口的来源"); } </script> </head> <body> <button onclick="callParentFunction()">调用父窗口函数</button> </body> </html>

在这个例子中,postMessage 用于在不同域的窗口之间安全传递消息,第二个参数是指定消息接收方的来源,以保证只有该来源的窗口能接收到消息。这样,即使是不同源的页面,也可以通过这种方式进行通信。

2024年6月29日 12:07 回复

你的答案