views:

995

answers:

4

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?

A: 

myWindow.document.writeln(documentString)

Giao
+1  A: 

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()

    }
Vijesh VP
+6  A: 

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.

Dan
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
nice, this is good to know.
matt lohkamp
A: 

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/

Greg Borenstein