js サブウィンドウから親ウィンドウに値を渡す(クロスドメイン)window.opener、window.open()、.postMessage()
サブウィンドウでセットした値を親ウィンドウに渡したい
作成日:2021-03-30, 更新日:2021-03-30
基本
・クロスドメインが絡む、絡まないで内容が少し異なる
・「window.open()」でサブウィンドウを開く
・「window.opener」で親ウィンドウに何かする
クロスドメインは絡まない
▼親
<form id="text_popup" name="text_popup"> <input type="text" name="input01"> ~ 略 ~ <script>var url = 〇〇〇〇; window.open(url, 'window_name', 'width=250,height=350,scrollbars=yes,resizable=yes,status=yes'); </script>
▼子
var set_form = function(fromSub_val){
if(!window.opener || window.opener.closed){ // メインウィンドウの存在をチェック
window.alert('メインウィンドウがありません'); // 存在しない場合は警告ダイアログを表示
return false;
}
var fm = window.opener.document.text_popup; //親ウィンドウの「name="text_popup"」
fm.input01.value = fromSub_val; //親ウィンドウの「input01」ドキュメント(nameが「input01」のinputタグへ値を代入
// fm.submit(); //親ウィンドウのフォームを送信
// // jqueryでセットする場合
// $(window.opener.document).find('#text_popup').find('[name="input01"]').val(fromSub_val);
// window.close(); // 自身を閉じる
return false;
}
set_form(〇〇〇);
クロスドメインが絡む
・postMessage()で値を渡す
・window.addEventListener()で値を受け取る
※参照:window.postMessage - Web API | MDN
▼親
<form id="text_popup" name="text_popup">
<input type="text" name="input01">
~ 略 ~
<script>
// postMessage()でやってきた値
window.addEventListener('message', function (e) {
switch (e.data.action) {
case 'form_val':
var elm_form = $('#text_popup');
$.each(e.data.message, function(key){
elm_form.find('[name="'+key+'"]').val(e.data.message[key]);
});
break;
}
});
var url = 〇〇〇〇;
window.open(url, 'window_name', 'width=250,height=350,scrollbars=yes,resizable=yes,status=yes');
</script>
▼子
var set_form = function(){
if(!window.opener || window.opener.closed){ // メインウィンドウの存在をチェック
window.alert('メインウィンドウがありません'); // 存在しない場合は警告ダイアログを表示
return false;
}
var form_val = ({
input01: '〇〇〇',
input02: '〇〇〇'
});
var postMessage = ({
action: 'form_val',
message: form_val
});
window.opener.postMessage(postMessage, '*');
// window.close(); // 自身を閉じる
return false;
}
set_form();
window.open()で使うオプション
| オプション | 対象部分 | yes (または 1) |
no (または 0) |
|---|---|---|---|
width= |
ウィンドウの横幅 | ピクセル数で指定 | |
height= |
ウィンドウの縦幅 | ピクセル数で指定 | |
scrollbars= |
スクロールバー | 表示可能にする | 表示しない |
resizable= |
ウィンドウのサイズ変更 | 変更を可能にする | 変更を禁止する |
menubar= |
メニューバー | 表示する | 表示しない |
toolbar= |
ツールバー | 表示する | 表示しない |
location= |
ロケーションバー | 表示する | 表示しない |
directories= |
ディレクトリバー | 表示する | 表示しない |
status= |
ステータスバー | 表示する | 表示しない |