0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

指定のタブ移動で空ページを表示させたくない

Posted at
  • window.openの引数2つ目には特定のタブ(のwindowName)を指定できるが、そのタブが存在しない場合には真っ白なページ(about:blank)が新規タブで開かれてしまう
  • 不格好なのでユーザには見せることなく、代わりにアラートやダイアログのような警告を表示したい
function focusOrOpenWindowByName(windowName, url = 'about:blank') {
    let win = window.open('', windowName);
    if (!win || win.closed) {
      // ウインドウを開けなかった場合
      return;
    }
    try {
      if (win.location.href !== 'about:blank') return;
      win.focus();
    } catch (e) {
      // CORSエラー等の場合
      try {
        win.focus();
      } catch (ex) {}
      return;
    }
    if (url !== 'about:blank') {
      // URLを開く
      win.location.href = url;
    } else {
      // 空白タブがある場合は閉じる
      win.close();
      // 警告する
      setTimeout(function () {
          window.alert("指定のタブがありません");
          // ユーザに選択させる場合
          // if (window.confirm("空ページを開きますか?")) {
          //     window.open('', windowName);
          // }
      }, 0);
    }
}
  • こうなる
    • windowNameをもつタブが存在しない ⇒ 警告
    • windowNameをもつ空タブが開かれている ⇒ 閉じて警告
    • windowNameをもつ空でないタブが開かれている ⇒ そのタブに移動
  • 一度開いてから閉じている所がポイント
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?