質問

ブラウザウィンドウを閉じたときにアラートを取得するために、次のコードを試しました:

window.onbeforeunload = confirmExit;
function confirmExit() {
  return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

動作しますが、ページに1つのハイパーリンクが含まれている場合、そのハイパーリンクをクリックすると同じアラートが発生します。ハイパーリンクをクリックしたときではなく、ブラウザウィンドウを閉じたときにのみアラートを表示する必要があります。

役に立ちましたか?

解決

コードをそのままにして、jQueryを使用してリンクを処理します。

$(function () {
  $("a").click(function {
    window.onbeforeunload = null;
  });
});

他のヒント

別の実装は、このWebページで見つけることができる次のとおりです。 http://ujap.de/index.php/view/JavascriptCloseHook

<html>
  <head>
    <script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Did you save your stuff?"
        }
      }
      function unhook() {
        hook=false;
      }
    </script>
  </head>
  <body>
    <!-- this will ask for confirmation: -->
    <a href="http://google.com">external link</a>

    <!-- this will go without asking: -->
    <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
  </body>
</html>

それは、フラグとして変数を使用することです。

ハイパーリンクのクリックは検出できますが、ユーザーが次のことを判断できません:

  • ページを更新しようとしました。
  • ブラウザタブを閉じようとしました。
  • ブラウザウィンドウを閉じようとしました。
  • URLバーに別のURLを入力し、Enterキーを押します。

これらのアクションはすべて、 window beforeunload イベントを生成します。イベントに関する詳細な情報はありません。

上記のアクションを実行するときに確認ダイアログを表示し、ハイパーリンクがクリックされたときに表示しないようにするには、次の手順に従います。

  • beforeunload イベントリスナーを window に割り当てると、確認テキストが文字列として返されます。特定の変数(フラグ)が code> true 。
  • click イベントを document に割り当てます。 a 要素がクリックされたかどうかを確認します( event.target.tagName )。はいの場合、フラグを true に設定します。

submit イベントリスナーを document に割り当てることで、フォーム送信も処理する必要があります。

コードは次のようになります。

let disableConfirmation = false;
window.addEventListener('beforeunload', event => {
  const confirmationText = 'Are you sure?';
  if (!disableConfirmation) {
    event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+
    return confirmationText;              // Gecko, WebKit, Chrome <34
  } else {
    // Set flag back to false, just in case
    // user stops loading page after clicking a link.
    disableConfirmation = false;
  }
});
document.addEventListener('click', event => {
  if (event.target.tagName.toLowerCase() === 'a') {
    disableConfirmation = true;
  }
});
document.addEventListener('submit', event => {
  disableConfirmation = true;
});
<p><a href="https://stacksnippets.net/">google.com</a></p>
<form action="https://stacksnippets.net/"><button type="submit">Submit</button></form>
<p>Try clicking the link or the submit button. The confirmation dialog won't be displayed.</p>
<p>Try reloading the frame (right click -> "Reload frame" in Chrome). You will see a confirmation dialog.</p>

一部のブラウザーでは、 beforeunload リスナーで event.returnValue を使用する必要があり、他のブラウザーでは return ステートメントを使用する必要があることに注意してください。

beforeunload イベントドキュメント

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top