开发者

Remove a DIV from within it's child IFRAME (cross-domain)

I'm working on a bookmarklet that loads Javascript from my server. The JS adds a div with an embedded iframe (so I can pass/load content from my own domain).

I cannot figure out how to remove the DIV element, including the iframe, from within the iframe. I can't reference window.parent because it is cross domain. window.postMessage looks like it might be the right idea, but I haven't found sufficient documentation that helps me understand it.

I would very much like to have 开发者_StackOverflow社区the iframe's close button within the iframe. Assistance is appreciated.

EDIT: In my attempt to use window.postMessage, I have tried creating an event listener with the bookmarklet (ergo, on any domain):

var receiveMessage = function(event) {
    $("#iframecontainerdiv").remove();
    console.log (event);
    alert (event.origin);
}
window.addEventListener("message", receiveMessage, false);

And then within the iframe, I tried to trigger it:

$("#abort").click( function(e) {
    e.preventDefault();
    window.close();
    window.postMessage("Hello, World!", "*");
});

I'm not sure if I'm going about this right...


I think you're posting the message to the wrong window. Maybe you should be using window.top.postMessage to post a message instructing the top window to remove the iframe.

So:

var receiveMessage = function(event) {
    if ("close-iframe" == event.data) {
        $("#iframecontainerdiv").remove();
    }
    console.log (event);
    alert (event.origin);
}
window.addEventListener("message", receiveMessage, false);

and:

$("#abort").click(function(e) {
    e.preventDefault();
    window.top.postMessage("close-iframe", "*");
});

You could optionally test the origin of the message so that only messages from your domain result in the iframe being removed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜