Giancarlo Corzo
Giancarlo Corzo

Reputation: 2026

cross-domain issue trying to call a js function from inside iframe to it's parent

Hi all I've a problem with cross domain.

I have 1 server (example.com) where I have:

index.html as main page, indexIFrame.html as a frame inside index.xhtml

Index.html loads a lot of javascript files from a static server (for example staticServer:8090/myScript.js)

Also indexIFrame.html load it's own javascript files from another static server (anotherServer:8070/myOtherScript.js)

So In myOtherScript.js I'm doing this:

parent.MyMainClass.showPopup();

MyMainClass class is declared in a js file from staticServer (this files is available to index.xhtml)

when I run the code I get:

Unsafe JavaScript attempt to access frame with URL http://example:8080/myapp/myList.xhtml from frame with URL http://example:8080/myapp/myListIFrame.xhtml Domains, protocols and ports must match.

myList and myListIframe they are in the same server only the javascript resources are in different domains.

So I'm not sure how to make this work. Any ideas?

Upvotes: 1

Views: 2051

Answers (2)

Steve Campbell
Steve Campbell

Reputation: 3605

Modern browsers simply do not allow this. The preferred technique is to use https://developer.mozilla.org/en-US/docs/DOM/window.postMessage instead.

...but you'll find, as usual, that IE is in its own little world and does not support that standard. I know there are some frameworks that provide a cross-browser solution, but I cannot specifically recommend any of them.

Here is a cross-browser listener:

if (typeof(window.postMessage) != 'undefined') {
    if (typeof(window.addEventListener) != 'undefined') {
        window.addEventListener("message", function(event) {
            doSomething(event.data);
        }, false);
    } else {
        window.attachEvent('onmessage', function(e) {
            doSomething(e.data);
        });
    }
}​

...and a sender...

if (typeof(window.postMessage) != 'undefined') {
    //modern browsers...
    window.top.postMessage('my data', '*');
} else {
    //older browsers - just access window.top
}

Upvotes: 1

kuncajs
kuncajs

Reputation: 1098

Try to create some aliases on server.

So that for example: http://example:8080/myapp/myScript.js leads to staticServer:8090/myScript.js and so on.

This might fool the javascript as it should think those JS files are really on your server.

Upvotes: 0

Related Questions