▲TOPへ戻る

【javascript】クリックして新しいウィンドウを開き、データを転送する方法、また子ウィンドウからデータを受け取る

windowOpen

新しくウィンドウを開く方法

  1. window.open(url, name, option);
<button onclick="openWindow('', '', 'width=400,height=300')">新しいウィンドウ</button>
<button onclick="openWindow('', '', '')">新しいタブ</button>
<button onclick="openWindow('https://yahoo.co.jp','name', '')">yahoo</button>

<script>
  function openWindow(url, name, option){
    window.open(url, name, option);
  }
</script>        

optionを入力すると、新しいウィンドウで開かれます。'' 空だと、新しいタブで開かれます。

window.opener

window.openerとは、そのページを開いた元のページを返します。

子ウィンドウでwindow.openerを使い、親ウインドウの要素を取得することができます。

子ウィンドウでこの文章を取得してみよう!!!(id="test")

// 子ウィンドウのjavascript
function parentProperty(){
  console.log(window.opener.document.getElementById("test").textContent);;
  // => 子ウィンドウでこの文章を取得してみよう!!!(id="test")
})

親子間のウィンドウでデータをやり取りする

まずはファイルを作成しましょう。

親ウィンドウと子ウィンドウのHTMLをそれぞれ作り、同じ階層におきます。

windowOpen

親ウィンドウ

<h1>親ウィンドウ</h1>
<h2>子ウィンドウへ転送</h2>
<!-- textareaの値が子ウィンドウへ -->
<textarea
  name="dataTransfer"
  id="parent-textarea"
  cols="30" rows="3"
></textarea><br>
<button onclick="openWindow('child-window.html', 'dataTransfer')">子ウィンドウへ転送</button><br><hr>

<h2>子ウィンドウから転送</h2>
<!-- 子ウィンドウのデータがinputに反映 -->
<input type="text" id="parent-input">
function openWindow(url, name) {
  window.open(url, name, "width=400,height=300");
}
// 親ウィンドウのjavascriptはこれだけです。

子ウィンドウ

<!-- ファイル名 child-window.html -->
<h1>子ウィンドウ</h1>
<!-- 親ウィンドウからのデータがこのtextareaに反映 -->
<textarea  
  name="dataTransfer"
  id="child-textarea"
  cols="30" rows="3"
></textarea><br /><hr />

<!-- inputの値が親ウィンドウへ -->
<input type="text" id="child-input" /><br />
<button onclick="returnData()">親ウィンドウへ転送</button>

onloadで子ウィンドウのページが読み込まれた段階で、 親ウィンドウからデータを取得します。

この処理を親ウィンドウで書くと、子ウィンドウがまだ開かれていないので、 エラーになります。

// 子ウィンドウ側のjavascript
window.onload = function () {
  // 親ウィンドウの存在チェック
  if (!window.opener || window.opener.closed) {
    window.alert("親ウィンドウがありません。");
    return false;
  }
  document.getElementById("child-textarea").value =
    window.opener.document.getElementById("parent-textarea").value;
};

// 親ウィンドウへ転送
function returnData() {
  // 親ウィンドウの存在チェック
  if (!window.opener || window.opener.closed) {
    window.alert("親ウィンドウがありません。");
    return false;
  }
  window.opener.document.getElementById("parent-input").value =
    document.getElementById("child-input").value;
}

デモページを開き、データのやり取りができていることを確認してください。

※注意 : もし自分のパソコンで試す場合、XAMPP等を使い、ローカルサーバー上で行ってください。

まとめ

  1. window.open()で、新しいウィンドウ(タブ)を開く
  2. window.openr()で、親ウィンドウの要素を取得
  3. 子ウィンドウが開かれた時に、親ウィンドウを取得し、子ウィンドウに反映させる。

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ