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

rka*_*yan 11 html javascript 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>
Run Code Online (Sandbox Code Playgroud)

这是代码 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>
Run Code Online (Sandbox Code Playgroud)

当我点击"点击这里"链接.我得到了以下错误.

未捕获的SecurityError:阻止具有原点" http://www.my-website.com "的框架访问具有原点" http://my-localhost.com " 的框架.协议,域和端口必须匹配.

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

Que*_*tin 17

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

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

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

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

addEventListener("message", receiveMessage, false);
Run Code Online (Sandbox Code Playgroud)

在另一个,发送消息:

parent.postMessage("This is a message", "*");
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅MDN


小智 11

你可以使用postMessage!

家长

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);
}
Run Code Online (Sandbox Code Playgroud)

IFRAME

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

参考

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