使用 window.open 和 window.name [英] using window.open with window.name

查看:69
本文介绍了使用 window.open 和 window.name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览器 window.open 方法提供了一种按名称访问打开窗口的方法.例如,

窗口 A:

The browser window.open method provides a way to access open windows by name. For example,

window A:

window.open('','myWindowName')

这将打开一个空白窗口 B,其中 window.name == 'myWindowName'.然后,

This will open a blank window B with window.name == 'myWindowName'. Then,

window.open('http://example.com', 'myWindowName')

这将在窗口 B 中打开 example.com.

This will open example.com in window B.

与其创建一个名称为 == 'myWindowName' 的新窗口,我该如何设置一个已经打开的窗口的名称,以便其他窗口可以使用 window.open 访问它?使用 Chrome 以下内容不起作用:

Rather than creating a new window with name == 'myWindowName', how can I set the name of an already opened window so that it can be accessed by other windows using window.open? Using Chrome the following does not work:

<!DOCTYPE html>
<html>
  <head>
    <script>window.name='myWindowName'</script>
  </head>
  <body>
    target window
  </body>
</html>

在目标窗口中执行 window.name 现在生成 'myWindowName'

executing window.name in the target window now produces 'myWindowName'

window.open('http://example.com', 'myWindowName')

上面的代码在一个新窗口(也带有 window.name 'myWindowName')而不是目标窗口中打开 example.com.

The code above opens example.com in a new window (also with window.name 'myWindowName') rather than the target window.

出于某种原因,在 chrome 中,如果没有内容加载到窗口中,则在目标窗口中设置名称将起作用,但是一旦加载内容,设置 window.name 不再影响其他窗口的 window.open.

for some reason, in chrome, setting the name in the target window will work if no content is loaded into the window, but once content is loaded setting window.name no longer affects the window.open of other windows.

推荐答案

正如上面评论中所建议的,为了使用 window.open 方法按名称定位一个窗口,目标窗口必须具有相同的来源并且有一个普通开瓶器.

As suggested in the comments above, in order to target a window by name using the window.open method, the target window must have the same origin AND have a common opener.

镀铬测试:

window.name = 'target'
window.was_open = true

2.打开新窗口 example.com(或任何网站)

w = window.open('', 'target')
w.was_open //undefined

不知道为什么在窗口控制台中执行 js 而没有先加载内容(例如 example.com)时,同样的测试会起作用.

It is unknown why the same test works when the js is executed in a window console without loading content first (like example.com).

不能从多个来源或具有不同开启者的窗口定位一个公共窗口.例如,小书签不能使用 window.open 将 postMessage() 用于公共窗口.

A common window cannot be targeted from multiple origins, or windows with different openers. For example, window.open cannot be used by a bookmarklet to postMessage() to a common window.

这篇关于使用 window.open 和 window.name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆