簡體   English   中英

關閉瀏覽器時顯示警告框,但不顯示頁面刷新或使用f5或瀏覽器刷新按鈕刷新

[英]Show alert box when closing browser, but not on page reload or refresh using f5 or browser refresh button

您好,我想在用戶關閉我的網站時向用戶顯示彈出窗口。 如何檢測此事件。 我有一個解決方案,但不適用於瀏覽器刷新點擊

var exit = true;
$(window).on("keydown",function(e){
    if(e.which === 116){
      exit = false;
    }
});
    $(window).bind("beforeunload", function() {
        if (exit === true) {
            return "Are you sure you want to leave?";
        } else {
            return;
        }
});

可以使用以下JavaScript非常簡單地完成...

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

編輯

我不知道有什么方法可以避免在用戶按下瀏覽器中的刷新按鈕時觸發該腳本,但是有一種方法可以在他們按下f5時將其停止...

jQuery的

//you need to set the variable exit to true first so it fires when f5 is not pressed
var exit = true;

//on keydown event will check if f5 is pressed
$(window).on("keydown",function(e){//begin window on keydown event

    //f5 key code is 116
    if(e.which === 116){//begin if it f5 is pressed

      //set exit to false so the prompt isn't displayed
      exit = false;

    }


});


//bind the beforeunload event to the window
$(window).bind("beforeunload", function() {

    //if exit = true then display the prompt
    if (exit === true) {

        //display the prompt
        return "Are you sure you want to leave?";
    } else {

        //do nothing, no prompt will be created
        return;

    }


});

不要忘記在<head>包含jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM