Question

I want to open a JQuery UI Dialog from an iframe, but I do not want the dialog to be a child of the iframe. I want it to be a child of the top window.

This question has been asked before, but I don't find the two answers to be satisfactory for my situation. What makes my situation different is that my iframe is from a different domain than the top window. They use the same host, but different protocols. The iframe is served under https, while the top window is served under http.


The answer with the most upvotes (by @Dmitry) says to use the jQuery object from the top window to open the dialog. like this:

window.top.jQuery.dialog(...);

This works when the iframe and the top window are from the same domain, but when they are not, the following error is thrown:

Error: Permission denied to access property 'jQuery'

The selected answer (by @CalebD) suggests the following:

Move your JavaScript so that it executes within the context of the parent document.

But it does not elaborate on how this can be accomplished. The only way I can see doing this is to have the iframe trigger an event on the document object of the top window, but that again will cause an error when the iframe uses a different domain than the top window.


My compromise for now is to use the following code to get the highest window that is usable.

var topWindow = (function() {
    var topW = window;
    while (topW.parent != topW.self) {
        try {
            var document = topW.parent.document; // Test
            topW = topW.parent;
        } catch(e) {
            return topW.self;
        }
    }
    return topW.self;
})(),

Then I can use:

topWindow.jQuery.dialog(...);

Of course, when the iframe uses a different domain, the dialog is a child of the iframe, but at least it works the way I want when the iframe is from the same domain.


Is there any way to open a dialog from the iframe so it is a child of the top window when the iframe and the top window are from different domains? Is there anything I can do better than what I am?

Was it helpful?

Solution

Same origin policy keeps you from interacting with that page.

You would need control of both domains and use window.postMessage() to pass details from one page to the other on what to do. The parent page would need to listen for the message and know how to open up the dialog.

OTHER TIPS

Use postMessage(). It's similar to events, but works cross-origin. This is pretty much the only way two frames from different domains are allowed to communicate, since it must be consensual (one must know a message would come, one would knowingly post a message).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top