1
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?

More than 3 years have passed since last update.

showModalDialogのように、サブウインドウを表示して戻り値を取得する

Posted at

やりたいこと

window.showModalDialogのように、サブウインドウを表示して戻り値を取得する。

実装

opener.js
function openWindowToCenter(name, url, width, height) {
  const left = (screen.width - width) / 2;
  const top = (screen.height - height) / 2;
  const param = `width=${width}, height=${height}, left=${left}, top=${top}`

  return window.open(url, name, param);
}

function lockBody(window) {
  window.document.body.style.pointerEvents = 'none';
}

function unlockBody(window) {
  window.document.body.style.pointerEvents = 'auto';
}

function showDialogAsync(url, width, height) {
  lockBody(window);

  const timestamp = Data.now().toString();
  const dialogName = `dialog_${timestamp}`;
  const dialog = openWindowToCenter(dialogName, url, width, height);

  return new Promise((resolve, reject) => {
    const intervalId = setInterval(() => {
      if (dialog.closed) {
        clearInterval(intervalId);

        unlockBody(window);

        resolve(window[dialogName]);
      }
    }, 100);
  });
}

(function () {
  document.getElementById('showDialogButton').onclick = async () => {
    const returnValue = await showDialogAsync('dialog.html', 100, 100);

    console.log(returnValue);
  };
}());
dialog.js
function returnValueToOpener(value) {
  window.opener[window.name] = value;

  window.close();
}

(function () {
  document.getElementById('returnValueButton').onclick = () => {
    returnValueToOpener('戻り値');
  };
}());
opener.html
<html>
  <head>
    <title>呼び出し元ウインドウ</title>
  </head>
  <body>
    <button type="button" id="showDialogButton">サブウインドウを開く</button>
    <script scr="opener.js"></script>
  </body>
</html>
dialog.html
<html>
  <head>
    <title>呼び出し先ウインドウ</title>
  </head>
  <body>
    <button type="button" id="returnValueButton">呼び出し元に値を返す</button>
    <script scr="dialog.js"></script>
  </body>
</html>

補足

ウインドウを閉じたときのイベントにはwindow.oncloseがあるが、標準仕様に含まれていないため使用しなかった。

1
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
1
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?