1

I have a <div> being dynamically created, and it contains an <iframe>. The <iframe> may close itself, at which point the <div> is removed.

So far I have:

var div = document.createElement('div'), ifr = document.createElement('iframe');
// some styles and stuff here, including ifr.src
ifr.contentWindow.container = div; // Note that domains are the same

// within the iframe's code, possibly a "close" link or after completing an operation
container.parentNode.removeChild(container);

It works. But only if the page within the iframe is the one that was there to start with. If a link is clicked to another page, window.container is no longer defined.

I know I can use window.name to store data persistent to a window, but that it limited to data that can be serialised. To my knowledge, you can't serialise a DOM node, other than by assigning it an ID and storing that. I would like to avoid such arbitrary IDs, so if anyone can suggest a better solution I would be very grateful.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592

2 Answers2

1

Use this code:

//At the frame:
var parentFrames = parent.document.getElementsByTagName("iframe");
for(var i=parentFrames.length-1; i>=0; i--){
    if(parentFrames[i].contentWindow == window) {
        parentFrames[i].parentNode.removeChild(parentFrames[i]); //Removes frame
        //Add an extra `.parent` at each side of the expression to remove the `div`.
        break;
    }
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Ah, yes. I already do something like this elsewhere in my code, don't know why I didn't think to apply that here :D Will give it a test, and let you know. – Niet the Dark Absol Sep 25 '11 at 12:21
  • I haven't explained the code, because I assumed that you're already quite advanced at programming in JS. If a part of the code is unclear, feel free to ask for clarification. – Rob W Sep 25 '11 at 12:23
0

Pages loaded into your <iframe> can use "window.parent" to get to the containing page. Thus, instead of keeping some "magic" reference in the <iframe>, keep it on the containing page and have the "child" pages look for it.

  function closeMe() { // inside the iframe page
    window.parent.frameContainer.removeChild(window.parent.removableFrame);
  }

In addition to "parent", the "top" property of "window" references the top-most context when there's a chain of windows (frames) longer than just one step (so, an <iframe> in an <iframe> etc).

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Solution works, but only if there is one such ` – Niet the Dark Absol Sep 25 '11 at 12:15
  • Well the "contentWindow" of the parent iframe should be == the window of the iframe, I think. I can check with a jsfiddle. – Pointy Sep 25 '11 at 12:16