如何调用iframe中的父窗口JavaScript函数 [英] How to Call Parent Window JavaScript Function inside iframe
问题描述
这是我的代码 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.
未捕获的SecurityError:阻止了一个框架与原点
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.
请帮助我修复此问题,或给出一些其他解决方案。 p>
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).
最近你可以来,然后只有在您控制这两个网站时,才会使用 Web messaging 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屋!