Pregunta

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

window A:

window.open('','myWindowName')

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

window C:

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

This will open example.com in window B.

The problem:

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:

1. open the following html in the target window

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

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

2. execute the following js from the console of another window

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

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

edit:

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.

¿Fue útil?

Solución

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.

chrome test:

1. open new window example.com (or any site)

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

2. open new window example.com (or any site)

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

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

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top