且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-09-01 11:43:10

您无法访问在不同来源的框架中加载的页面的 DOM.这是出于安全原因被阻止的(想象一下您访问的随机网站在隐藏的 iframe 中打开您的网络邮件服务,您可以看到原因).

You cannot access the DOM of a page loaded in a frame in a different origin. This is blocked for security reasons (imagine a random website you visited opening your web mail service in a hidden iframe and you can see why).

最接近的方法是使用 网络消息 API.

The closest you can come, and then only if you control both websites, is to pass messages between them using the web messaging api.

在一个页面中,编写一个函数来处理消息,然后将其添加为消息事件侦听器.

In one page, write a function to handle the messages and then add it as a message event listener.

function receiveMessage(event)
{
  alert(event.data);
}

addEventListener("message", receiveMessage, false);

在另一个中,发送消息:

In the other, send the message:

parent.postMessage("This is a message", "*");

请参阅 MDN 了解更多信息