如何在 HTML5 中控制另一个窗口?
我正在尝试在 HTML5 中控制另一个窗口。我希望这样当我打开一个登录的窗口和另一个登录的窗口时,我可以从一个窗口单击一个按钮,然后在另一个窗口中发生一些事情。我不知道从哪里开始;有人能指出我正确的方向吗?
I'm trying to control one window from another in HTML5. I'd like it so when I open one window that I log into, and another window that I login to, then from one window I can click a button and something happens in the other window. I'm not sure where to start; can somebody point me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要任何 HTML5 功能,但您可以使用 javascript 轻松实现:
myNewWindow = window.open()
打开一个新窗口并分配一个window
-该新窗口的对象到myNewWindow
,这样您就可以使用myNewWindow
变量从打开脚本轻松访问新窗口的 DOM。它还可以以另一种方式工作:在新窗口中的脚本中,您可以使用
window.opener
来访问打开窗口的window
对象和 DOM。只需确保所有窗口的内容都是从同一域加载的,因为 javascript 不允许您控制从其他源加载的内容(有关此主题的更多信息,请参阅“同源策略”)。
You don't need any HTML5-Features for that but you can easily do it with javascript:
myNewWindow = window.open()
opens a new window and assigns awindow
-object of that new window tomyNewWindow
, so you can easily access the new window's DOM from the opening script, using themyNewWindow
-variable.It also works the other way: In a script in the new window, you can user
window.opener
to access thewindow
-object and DOM of the opening window.Just make sure, that the content of all your windows is loaded from same domain, as javascript does not allow you to control content loaded from another source (refer to "same origin policy" for more information on this topic).
这个答案晚了 6 个月,但对于 Google 员工(比如我)来说:
我会推荐 WebSockets 来完成您想要做的事情,乔纳森。 WebSocket 允许服务器将数据实时广播到为您的页面/站点打开的任何/所有浏览器窗口。
目前浏览器支持相当差,但有一些很好的垫片可以让它在所有浏览器上非常有效地工作。 Socket.io 就是这样一种解决方案,我使用它取得了巨大成功。
This answer is 6 months late, but for the Googlers (like me):
I would recommend WebSockets for what you're trying to do Jonathan. WebSockets allow the server to broadcast data to any/all browser windows that are open for your page/site in realtime.
Browser support is currently quite poor but there are good shims to get it working across all browsers very efficiently. Socket.io is one such solution which I've used to great success.