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

时间:2013-10-16 14:46:28

标签: javascript html iframe cross-domain

以下是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>

当我点击“点击此处”链接时。我得到了以下错误。

  

Uncaught SecurityError:阻止具有原点的帧   “http://www.my-website.com”访问具有原点的框架   “http://my-localhost.com”。协议,域和端口必须匹配。

请帮我解决此问题,或者为此提供一些其他解决方案。

2 个答案:

答案 0 :(得分:17)

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

您可以来的最近,只有当您控制两个网站时,才能使用web messaging api在它们之间传递消息。

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

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

addEventListener("message", receiveMessage, false);

在另一方面,发送消息:

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

请参阅MDN for more information

答案 1 :(得分:11)

您可以使用postMessage!

PARENT

if (window.addEventListener) {
    window.addEventListener ("message", receive, false);        
}
else {
    if (window.attachEvent) {
        window.attachEvent("onmessage",receive, false);
    }
}

function receive(event){
    var data = event.data;
    if(typeof(window[data.func]) == "function"){
        window[data.func].call(null, data.params[0]);
    }
}

function alertMyMessage(msg){

    alert(msg);
}

IFRAME

function send(){
    window.parent.window.postMessage(
        {'func':'alertMyMessage','params':['Thanks for Helping me']},
        'http://www.my-website.com'
    );
}

参考

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

相关问题