iframe 上的持久变量?
我有一个动态创建的
,它包含一个
。
可能会自行关闭,此时
会被删除。到目前为止我已经:
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);
它有效。但前提是 iframe 中的页面是一开始的页面。如果单击链接到另一个页面,则不再定义 window.container
。
我知道我可以使用 window.name 来存储持久到窗口的数据,但它仅限于可以序列化的数据。据我所知,除了为其分配一个 ID 并存储它之外,您无法序列化 DOM 节点。我想避免这种任意的 ID,所以如果有人能提出更好的解决方案,我将非常感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用此代码:
Use this code:
加载到
中的页面可以使用“window.parent”来访问包含页面。因此,不要在
中保留一些“神奇”引用,而是将其保留在包含页面上并让“子”页面查找它。
除了“parent”之外,当存在比一步长的窗口(框架)链时,“window”的“top”属性引用最顶层的上下文(因此,
在
等中)。
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.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).