Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

javascript - Allowing a child Iframe to call a function on its parent window from a different domain

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...