开发者

Persistent variable on iframe?

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.


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


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).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜