TAGjQuery
ブラウザの戻るボタンクリック後離脱防止のポップアップを表示する方法:jQuery
ブラウザの戻るボタンをクリックされた後に、
離脱防止用のポップアップを表示する方法をメモ
HTML、CSS部分
<div class="popup-area"> <div class="close-btn"><img src="img/batu.png" alt="閉じる"></div> <div class="popwrap"> <!-- ここに表示する内容 --> </div> </div>
.popup-area {
display:none;
width:80vw;
padding:0;
position: fixed;
z-index: 9999;
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
text-align: center;
border-radius:0;
}
.popup-area .popwrap{
position:relative;
margin-bottom:20px;
box-shadow: 0 0 4px 4px rgba(0,0,0,0.4);
}
@media screen and (min-width: 980px) {
.popup-area {
width:auto;
max-width: 50vw;
}
}
.cover-eml {
background:rgba(0,0,0,0.6);
width: 100%;
height: 100%;
position: fixed;
z-index: 999;
top:0;
right:0;
bottom:0;
left:0;
}
.popup-area .close-btn{
margin: 0 0 15px auto;
cursor: pointer;
text-align:right;
width:15px;
height:15px;
}
jQuery
<script>
"use strict";
//非表示の判定
let popAppend = false;
//履歴の追加
let hash = location.hash;
if(hash != '#back') {
history.pushState(null,null,location.href);
history.replaceState(null,null,'#back');
}
//設定したハッシュタグが消えたら実行
window.addEventListener('popstate',(e) => {
if(location.hash != "#back" && popAppend === false) {
jQuery('.popup-area').fadeIn();
jQuery('body').append(jQuery("<div>", {class: 'cover-eml'}));
popAppend = true;
if(popAppend) {
jQuery('body').on('click', '.cover-eml' , function() {
deleteElm();
popAppend = false;
});
}
}
});
//表示削除
jQuery('body,.close-btn').click(function() {
deleteElm();
popAppend = false;
});
function deleteElm() {
jQuery('.cover-eml').fadeOut();
jQuery('.cover-eml').remove();
jQuery('.popup-area').fadeOut();
}
</script>
でOK
この方法はURLに#back等のパラメータが付くため、URLを変更したくない場合は微妙ですが、
パラメータを付けないとスマホで実装が難しそうな感じでしたので必須なのかなと思います。
LP等で離脱防止したい場合に便利です。

