ハイパーリンクのクリックを検出できますが、ユーザーが次のことを行っているかどうかを判断することはできません。
- ページを更新しようとしました。
- ブラウザのタブを閉じようとしました。
- ブラウザ ウィンドウを閉じようとしました。
- URL バーに別の URL を入力し、Enter キーを押します。
これらのアクションはすべて でイベントを生成beforeunload
しますがwindow
、イベントに関する正確な情報はありません。
上記のアクションを実行するときに確認ダイアログを表示し、ハイパーリンクがクリックされたときに表示しないようにするには、次の手順に従います。
- 特定の変数 (フラグ) が に設定されていない限り、確認テキストを文字列として返す
beforeunload
イベント リスナーをに割り当てます。window
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>
一部のブラウザーではリスナーで使用する必要があり、他のブラウザーではステートメントを使用することに注意しevent.returnValue
てbeforeunload
くださいreturn
。
beforeunload
イベント ドキュメントも参照してください。