javascript - Using a variable from a different window -


i want open new window in javascript, , show data opener window. based on read made this:

mainwindow.html

<html>  <head> <script> function opennewwindow() {     this.mainwindowdata = 123123;     document.write(this.mainwindowdata);      var wnd = window.open("newwindow.html");     wnd.newwindowdata = 787878; } </script> </head>  <body> <input type="button" value="open window" onclick="opennewwindow()"> </body>  </html> 

newwindow.html:

<html>  <head> <script> function showdata() {     document.write("newwindowdata: " + this.newwindowdata + "<br />");     document.write("mainwindowdata: " + window.opener.mainwindowdata); } </script> </head>  <body> <input type="button" value="show data" onclick="showdata()"> </body>  </html> 


problem both variables remain undefined.
in advance.

the problem isn't variables you're creating, it's document.write wipes out window's content when call time except during initial rendering, , wipes out variables you're creating after create them. don't want use after initial rendering.

if change document.write calls (say) document.getelementbyid('someid').innerhtml = ...; or use document.createelement, you'll more successful results.

here pages, changing document.write using document.createelement, makes them work.

main window: live copy | source

<html> <head> <script> function opennewwindow() {     this.mainwindowdata = 123123;      var wnd = window.open("http://jsbin.com/uvocos/1");     wnd.newwindowdata = 787878; } </script> </head>  <body> <input type="button" value="open window" onclick="opennewwindow()"> </body>  </html> 

popup window: live copy | source

<html> <head> <script> function showdata() {     display("newwindowdata: " + this.newwindowdata);     display("mainwindowdata: " + window.opener.mainwindowdata); }  function display(msg) {     var p = document.createelement('p');     p.innerhtml = string(msg);     document.body.appendchild(p) } </script> </head>  <body> <input type="button" value="show data" onclick="showdata()"> </body>  </html> 

the createelement in display function added popup.

separately: use window rather this create variable. this be window way you're calling functions, works, there other ways call functions wouldn't work, , using window.foo = ...; would.

finally: i'm not putting variable on popup immediately after opening (your newwindowdata) work reliably, although in above (for me). rather that, have popup pull data opener (your mainwindowdata variable) and/or pass data popup via query string.


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -