【javascript】子ウィンドウから親ウィンドウを更新

その他

概要

  • 子ウィンドウから親ウィンドウを更新できます。
  • 同一ドメイン内であれば、問題なく使用できます。

内容

index.html

  • window.openで子Windowを開きます。
<html lang="ja">
<head>
<meta charset="utf-8">
<title>親画面</title>
<script>
function openNewWindow(){
  window.open('./sub.html',null, 'top=100, left=500, width=1000, height=850');
}
</script>
</head>
<body>
  <input type="text" id="parentTxt" value="親Window">
  <input type="button" value=" 子ウィンドウを開く " onclick="openNewWindow();">
</body>
</html>

sub.html

  • 親のデータにはwindow.openerでアクセスできます。
  • 例えば、window.opener.document.getElementById(‘parentTxt’)のようにアクセスして、値を設定することができます。
  • 親Windowが、既に無くなっている場合には、「親が既に閉じられています。」のメッセージが出されます。
<html lang="ja">
<head>
<meta charset="utf-8">
<title>子画面</title>
<script>
function send(){
  if(!window.opener || window.opener.closed){
    alert("親が既に閉じられています。");
    return false;
  }
 
  var child = document.getElementById('childTxt').value;
  //親にデータを反映
  if(window.opener.document.getElementById('parentTxt') != null){ 
    window.opener.document.getElementById('parentTxt').value = child;
  }
}
</script>
</head>
<body>
  <input type="text" id="childTxt" value="子Window">
  <input type="button" value="親に反映" onclick="send();">
</body>
</html>

その他

jqueryを使用している場合、$(function () {})でくくって使用しますが、この場合は、子Windowから親Windowの関数が見えなくなります。

この場合、親Window側は、以下のように関数を見えるように定義し直せば、子Windowから、親Windowの関数を呼び出せます。

global_value_1は、javascriptのグローバル変数で、子Windowsから呼び出されても、問題なく作用します。

$(function () {
	
	//子Windowとのインターフェイス
	$.func_set= func_set;

	function func_set (value ) {
		global_value_1 = value;
		displayAverage();

	}

});

子Window側は、以下のようにします。

window.opener.$.func_set(valueA);

親画面
スポンサーリンク
その他
Engineerをフォローする
レンサバ