LoginSignup
16
18

More than 5 years have passed since last update.

【JavaScript】サブウインドウ

Last updated at Posted at 2015-04-01

サブウインドウの開き方

// window.open( URL, ウィンドウ名 [,オプション] )
window.open( 'http://www.yahoo.co.jp/','yahoo',null)

オプションは、パラメータをカンマ区切りで設定する。
以下の例はwidth=400, height=300で開いている。

window.open( 'http://www.yahoo.co.jp/','yahoo','width=400, height=300')

ちなみに、第二引数のウィンドウ名の箇所をnullにすると、新規タブになる。target="_blank" と同等。

参考:window.open()で小窓

サブウインドウでPOST後に、親ウインドウを更新して、サブウインドウを閉じる。

$('form').submit(function(){
  $.ajax({
    url: $(this).attr('action'),
    type: 'get',
    data: $(this).serialize(),
    dataType: 'html'
  })
  //POSTが完了後に処理を行う。
  .always(function(){
    //親ウインドウの関数(func_update)を使い、親ウインドウを更新
    window.opener.func_update;
    //サブウインドウを閉じる
    window.close();
  })

  return false;
})

window.openerで親ウインドウのwindowオブジェクトにアクセスできる。
今回は親ウインドウを単に更新するわけでないので関数を呼び出しているが、単に更新ならばwindow.opener.location.reload()でも良い。

また、ネットでみつけた以下の例だとそもそもPOSTされなかったり、ポストできたとしても、ポストと親ウインドウの更新が同じタイミングになってしまうので、always()を使って、ポストが終わってから親ウインドウの更新と、サブウインドウを閉じている。

うまくいかなかった例
$('form').submit();
window.opener.location.reload();
window.close();
16
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
18