I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas?
4 Answers
The reference returned by window.open()
is to the child window's window
object. So you can do anything you would normally do, here's an example:
var myWindow = window.open('...')
myWindow.document.getElementById('foo').style.backgroundColor = 'red'
Bear in mind that this will only work if the parent and child windows have the same domain. Otherwise cross-site scripting security restrictions will stop you.

- 61,568
- 9
- 61
- 78
-
It's actually the same origin policy (http://www.w3.org/html/wg/html5/#same-origin) which basically means you must be accessing a page on the same domain, on the same port, and with the same protocol (eg. https://example.com cannot write to http://example.com, https://example.com:8080, etc) – olliej Oct 04 '08 at 07:34
-
what goes where the dots are? – Simon Woodward Nov 23 '19 at 21:27
I think this will do the trick.
function popUp(){
var newWindow = window.open("","Test","width=300,height=300,scrollbars=1,resizable=1")
//read text from textbox placed in parent window
var text = document.form.input.value
var html = "<html><head></head><body>Hello, <b>"+ text +"</b>."
html += "How are you today?</body></html>"
newWindow .document.open()
newWindow .document.write(html)
newWindow .document.close()
}

- 4,508
- 6
- 30
- 32
The form solution that Vijesh mentions is the basic idea behind communicating data between windows. If you're looking for some library code, there's a great jQuery plugin for exactly this: WindowMsg (see link at bottom due to weird Stack Overflow auto-linking bug).
As I described in my answer here: How can I implement the pop out functionality of chat windows in GMail? WindowMsg uses a form in each window and then the window.document.form['foo'] hash for communication. As Dan mentions above, this does only work if the window's share a domain.
Also as mentioned in the other thread, you can use the JSON 2 lib from JSON.org to serialize javascript objects for sending between windows in this manner rather than having to communicate solely using strings.
WindowMsg:
http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/

- 1
- 1

- 1,536
- 2
- 13
- 18