在父级中导航到其他位置后,是否可以在 JavaScript 中重用弹出窗口?
假设我们有一个网站,您在其中单击一个按钮,然后使用 JavaScript 打开一个弹出(子)窗口。因此,我们将父级称为 A,将弹出窗口称为 P。在A的源码中,我们会看到这样的内容:
<script type="text/javascript">
P = window.open('P.html', 'P');
</script>
所以只要A打开,我们就可以在JavaScript中与P交互使用 P
变量。但是,当我单击 A 中的链接转到 B.html
时,我丢失了所有变量。然而我的弹出窗口仍然打开,所以我想知道是否有任何方法可以将两者重新链接在一起。有什么方法可以从B内部操纵P吗?非常感谢。
Suppose we have a website in which you click on a button, and that opens a popup (child) window using JavaScript. So let's call the parent A and the popup P. In the source of A, we'd see something like this:
<script type="text/javascript">
P = window.open('P.html', 'P');
</script>
So as long as A is open, we can interact with P in JavaScript using the P
variable. However, when I click on a link in A to go to B.html
, I lose all the variables. Yet my popup window is still open, so I wonder if there's any way I can link the two back together. Is there any way I can manipulate P from within B? Thanks much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
令我惊喜的是,我发现答案是肯定的。 Mohammad 使用
window.top
的解决方案不正确;当我尝试从 P 内访问window.top
时,它只会返回对 P 本身的引用。 RobG 的回答有点没有抓住重点。我发现,如果我在 P 内定期执行此操作,一切都会正常:
这样,即使我将父窗口从 A 导航到 B ,B 仍将使用对 P 的窗口引用进行更新,一旦建立,两个窗口就可以再次自由地相互通信。
Well I figured out that, to my pleasant surprise, the answer is YES. Mohammad's solution of using
window.top
was not correct; when I try to accesswindow.top
from within P, that just returns a reference to P itself. RobG's answer just kind of missed the point.I found that if I do this periodically from within P, everything works:
This way, even when I navigate the parent window from A to B, B will still be updated with a window reference to P and once that's established the two windows can then communicate freely with each other again.
窗口可以访问它打开的子窗口,子窗口也可以访问其打开器窗口。如果其中一个窗口导航到不同域中的新 URI,则另一个窗口将无法再访问其内容。
例如
Opener 窗口 HTML:
popWin.js:
如果您打开 opener 文档,则单击按钮将生成一个子窗口。单击子窗口中的按钮将显示打开文档的标题。将打开程序导航到新域,然后单击子窗口中的按钮,您会收到访问被拒绝的错误消息,如下所示:
A window can access child windows that it opens, and child windows can access their opener window. If either of the windows navigates to a new URI in a different domain, their content is no longer accessible to the other.
e.g.
Opener window HTML:
popWin.js:
If you open the opener document, then click on the button a child window is spawned. Clicking on the button in the child window will show the title of the opener document. Navigate the opener to a new domain then click on the button in the child window and you get an access denied error message, something like:
如果弹出窗口是最上面的窗口,您可以使用
window.top
从 B 中访问它,这里有一个包含更多详细信息的链接 window.topif the popup is the top most window you can use
window.top
to access it from within B here is a link with more details window.top