如何在 iframe 中调用父窗口 JavaScript 函数 [英] How to Call Parent Window JavaScript Function inside iframe

查看:23
本文介绍了如何在 iframe 中调用父窗口 JavaScript 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 http://my-localhost.com/iframe-test.html

<html>
<head><title>Welcome Iframe Test</title></head>
<body>
<iframe src="http://www.my-website.com/index.html" width="500" height="500"></iframe>
<script type="text/javascript">
function alertMyMessage(msg){
    alert(msg);
}
</script>
</body>
</html>

这是http://www.my-website.com/index.html

<html>
<head></title>Welcome to my Server</title></head>
<body>
<h1>Welcome to My Server</ht>
<a href="javascript:void(0)" title="Click here" onClick="parent.alertMyMessage('Thanks for Helping me')">Click Here</a>
</body>
</html>

当我点击点击这里"链接时.我收到以下错误.

When i Click the "Click Here" Link. i got following Error.

未捕获的安全错误:用原点阻止了一个框架http://www.my-website.com" 来自访问带有原点的框架http://my-localhost.com".协议、域和端口必须匹配.

Uncaught SecurityError: Blocked a frame with origin "http://www.my-website.com" from accessing a frame with origin "http://my-localhost.com". Protocols, domains, and ports must match.

请帮助我解决此问题,或为此提供其他解决方案.

Please Help me to Fix this Issue, or give some other solution for this.

推荐答案

您无法访问在不同来源的框架中加载的页面的 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 了解更多信息

这篇关于如何在 iframe 中调用父窗口 JavaScript 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆