2007-07-16 JavaScriptでWindow間で値のやり取り
■[javascript]JavaScriptでWindow間で値のやり取り

JavaScriptで子供のWindowを開き、子供のWindowから親のWindowの値を変える方法です。
■仕組み

JavaScriptで開いたWindowでしか操作できないのでJavaScriptで子供のWindowを開きます。
window.open("windowchild.html", "newWindow", "width=640,height=480");
子供の、Windowでは、opener.documentで親Windowのdocumentを参照できます。
opener.document.forms[0].elements["inp_value"].value="childvalue"; window.close();
■ソース

ユーザが、textフィールドの値を入力するかわりに、新しいダイアログ(Window)を開いて値を選択する例です。
FORMのinput type="text"の値を新しい子供のWindowを開いて、子供のWindowから変更します。
親Window
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>自宅サーバテスト</title> <script type="text/javascript"> //<![CDATA[ function windowopen() { var newW = window.open("windowchild.html", "newWindow", "width=640,height=480"); } //windowopen(); //]]> </script> </head> <body> 自宅サーバ <form method="POST" action="windowresult.php"> <br /> <input type="submit" name="submit" value="送信" /> <br /> <input type="submit" name="cancel" value="キャンセル" /> <br /> <input type="text" name="inp_value" value="Hoge" /> <div onclick="windowopen();">Windowオープン</div> </form> </body> </html>
子供Window
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>自宅サーバテスト</title> <script type="text/javascript"> //<![CDATA[ function setParentForm() { //opener.moveTo(0,0); opener.document.forms[0].elements["inp_value"].value="childvalue"; window.close(); } //]]> </script> </head> <body> 自宅サーバ Child window <input type="submit" value="親Windowに設定" onclick="setParentForm();" /> </body> </html>
結果
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>自宅サーバテスト</title> <script type="text/javascript"> //<![CDATA[ //]]> </script> </head> <body> <h1>結果</h1> PATH: <?php echo $_POST["inp_value"]; ?> <br /> SUBMIT: <?php echo $_POST["submit"]; ?> <br /> CANCEL: <?php echo $_POST["cancel"]; ?> <br /> </body> </html>
コメントを書く