4
3

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 5 years have passed since last update.

離脱防止モーダルを作ってみた

Last updated at Posted at 2017-09-26

離脱防止のモーダルの作成

離脱防止モーダルを作成したのでその時のメモ。

コード


const onBeforeunloadHandler = (e) => {
  const val = e;
  val.returnValue = '';
};

window.addEventListener('beforeunload', onBeforeunloadHandler);

動き

この数行でユーザーがアクションを起こし、
ページ遷移をしようとすれば離脱防止のアラートが出てくる。

ちなみにdefaultで
「このサイトを離れてもよろしいですか?」とアラートが表示される。
val.returnValue = '';で
アラートに表示する文字を設定できたみたいなのですが
現在はできなくなっているみたいです。(でも、このコード入れないとエラー起こすかも)

予想外の出来事

今回、実装にあたり予想外の出来事が起きた。
ページにアクセスしてアクション(スクロールしたり、クリックしたり)しないで
クローズボタン、戻るボタンを押すと離脱アラートが出てこない。

これは仕様らしいです。。

4
3
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?