JavaScriptのwindow.open()で別ウィンドウを開き、値をやり取りする

クリック処理の中でwindow.open()を呼び出し、返されたウィンドウ参照とpostMessage()を使って値をやり取りします。この例では、子ウィンドウが受信の準備を知らせてから初期値を送ります。受信側ではオリジン、送信元のウィンドウ、データの内容を確認します。

ウィンドウまたはタブを開く

window.open(url, target, features)のtargetには、再利用するウィンドウ名または_blankなどのキーワードを指定します。popup,width=420,height=320は小さなポップアップを要求する指定です。ブラウザーの設定によってはタブで開いたり、サイズが変わったりします。呼び出しはクリック処理内で直接行います。この例のようにnoopenerを指定しない呼び出しでnullが返った場合は、ウィンドウを開けなかったときの処理を行います。 HTML Standard · window.open()

メッセージの送信元を確認する

オリジンはプロトコル、ホスト、ポートの組み合わせです。たとえばhttp://localhost:8000とhttp://127.0.0.1:8000は別のオリジンです。異なるオリジンのウィンドウは互いのDOMに直接アクセスできません。postMessage(data, targetOrigin)に受信側の正確なオリジンを指定し、受信時にはevent.origin、event.source、メッセージの種類、値の型を確認します。 HTML Standard · postMessage()

2つのファイルで値をやり取りする

2つのコードを同じフォルダーにparent.htmlとchild.htmlとして保存します。Python 3がインストールされていれば、そのフォルダーで次のコマンドを実行し、http://127.0.0.1:8000/parent.htmlを開きます。同じアドレスから配信することで、2つの文書のlocation.originが一致します。

python -m http.server 8000 --bind 127.0.0.1

parent.html — 親ウィンドウはreadyを受け取ると、その時点で入力欄にある値をinitialメッセージで送ります。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>親ウィンドウ</title>
</head>
<body>
<label for="value">親ウィンドウの値</label>
<input id="value" value="初期値">
<button id="open" type="button">子ウィンドウを開く</button>
<p id="status" role="status"></p>
<script>
const input = document.querySelector('#value');
const status = document.querySelector('#status');
const origin = location.origin;
let child = null;

document.querySelector('#open').addEventListener('click', () => {
  child = window.open('child.html', 'valueExample', 'popup,width=420,height=320');
  status.textContent = child ? "子ウィンドウからの応答を待っています。" : "ポップアップを開けませんでした。";
});

window.addEventListener('message', event => {
  if (!child || event.origin !== origin || event.source !== child) return;

  const data = event.data;
  if (data?.type === 'ready') {
    child.postMessage({ type: 'initial', value: input.value }, origin);
  } else if (data?.type === 'result' && typeof data.value === 'string') {
    input.value = data.value;
    status.textContent = "子ウィンドウから値を受け取りました。";
  }
});
</script>
</body>
</html>

child.html — 子ウィンドウは初期値を受け取った後に送信ボタンを有効にします。ボタンを押すと、編集した文字列をresultメッセージで送り返します。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>子ウィンドウ</title>
</head>
<body>
<label for="child-value">子ウィンドウの値</label>
<input id="child-value">
<button id="send" type="button" disabled>親ウィンドウへ送信</button>
<p id="child-status" role="status"></p>
<script>
const input = document.querySelector('#child-value');
const send = document.querySelector('#send');
const status = document.querySelector('#child-status');
const origin = location.origin;
const openerWindow = window.opener;

if (!openerWindow) {
  status.textContent = "親ウィンドウのボタンからこのページを開いてください。";
} else {
  window.addEventListener('message', event => {
    if (event.origin !== origin || event.source !== openerWindow) return;

    const data = event.data;
    if (data?.type !== 'initial' || typeof data.value !== 'string') return;
    input.value = data.value;
    status.textContent = "親ウィンドウから値を受け取りました。";
    send.disabled = false;
  });

  openerWindow.postMessage({ type: 'ready' }, origin);
}

send.addEventListener('click', () => {
  if (send.disabled) return;
  if (openerWindow.closed) {
    send.disabled = true;
    status.textContent = "親ウィンドウは閉じています。";
    return;
  }
  openerWindow.postMessage({ type: 'result', value: input.value }, origin);
  status.textContent = "親ウィンドウへ値を送信しました。";
});
</script>
</body>
</html>

親の入力欄に123を入力して子ウィンドウを開くと、子の入力欄に123が表示されます。子の値を456に変更して送信すると、親の入力欄も456になります。演習を終えるには子ウィンドウを閉じ、サーバーを起動した端末でCtrl+Cを押します。

値が届かないときの確認点

ウィンドウが開かないときは、ブラウザーのポップアップ設定を確認してボタンを押し直します。送信ボタンが無効のままなら、両ページのオリジンが一致しているか、親のボタンから子を開いたかを確認します。親を閉じた後に送信しようとすると、子ウィンドウに案内が表示されます。

この例では2つの文書が通信できるよう、開いた側への参照を残しています。通信が不要な外部ページでは、リンクにrel="noopener"を指定するか、window.open()のnoopenerオプションを使って接続を切れます。この指定ではタブが正常に開いてもnullが返ることがあります。文書の分離ポリシーで参照が切れることもあります。