允许子项Iframe在其父窗口上从其他域调用函数 [英] Allowing a child Iframe to call a function on its parent window from a different domain

查看:126
本文介绍了允许子项Iframe在其父窗口上从其他域调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个在IFrame中加载的页面,它需要在加载完成后在父页面上调用一个函数。



它在本地开发(在同一个域),但在现实世界中,它托管在一个完全不同的域,所以显然我遇到跨域问题,即:



不安全的JavaScript尝试访问框架与URL http:// [...] site1.com从框架与URL http:// [...] site2.com/iframe。域,协议和端口必须匹配。



我控制两个服务器,所以我可以在一个或两个服务器上放置一些东西,允许彼此交谈?



我已经在Iframe页面和父页面中查看了设置document.domain。



我已尝试设置访问控制标题:



标题('Access-Control-Allow-Origin:*');



但是这两个都不工作。



有什么方法允许一个Iframe在父窗口中调用一个完全不同的域上的函数


解决方案

您可以通过消息发布API



例如,在子帧中,您可以调用:

  parent.postMessage(child frame,*); 

在父框架中,注册一个消息处理程序:

  window.addEventListener(message,function(event){
console.log(Hello from+ event.data);
} );


I have made a page which gets loaded in an IFrame and it needs to call a function on the parent page after it finishes loading.

It works locally in development (on the same domain) but in the Real World it is hosted on a completely different domain, so obviously I am running into Cross domain problems, ie:

Unsafe JavaScript attempt to access frame with URL http://[...]site1.com from frame with URL http://[...]site2.com/iframe. Domains, protocols and ports must match.

I control both the servers, so is it possible for me to put something on one or both of the servers that says they're allowed to talk to each other?

I have looked at setting "document.domain" in both the Iframe page and the parent page.

I have experimented with setting the Access Control Header:

header('Access-Control-Allow-Origin: *');

But neither of those work.

Is there any way of allowing an Iframe calling a function in the Parent window on a completely different domain when I control both servers?

解决方案

You can communicate between frames via the message posting API.

For example, in your child frame you might call:

parent.postMessage("child frame", "*");

And in the parent frame, register a message handler:

window.addEventListener("message", function(event) {
    console.log("Hello from " + event.data);
});

这篇关于允许子项Iframe在其父窗口上从其他域调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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