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

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

问题描述

我制作了一个页面,它被加载到 IFrame 中,它需要在加载完成后调用父页面上的一个函数.

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:

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

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?

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

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: *');

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

但这些都不起作用.

当我控制两台服务器时,是否有任何方法允许 Iframe 在完全不同的域上的父窗口中调用函数?

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?

推荐答案

您可以通过 消息发布 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天全站免登陆