Javascript How to call a function when we choose Stay on Page in Chrome

后端 未结 3 861
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 18:35

Please check my code in Chrome Browser, if you hit refresh you will be prompted with 2 options.

  1. Leave This Page and
  2. Stay on This Page
3条回答
  •  情书的邮戳
    2021-02-13 18:57

    You can use a combination of the onbeforeunload and onunload events, setting a timer in the former and clearing it in the latter:

    var showMsgTimer;
    
    window.onbeforeunload = function(evt) {
        var message = 'Please Stay on this page and we will show you a secret text.';
        showMsgTimer = window.setTimeout(showMessage, 500);
    
        evt = evt || window.evt;
        evt.returnValue = message;
    
        return message;
    }
    
    window.onunload = function () {
        clearTimeout(showMsgTimer);
    }
    
    function showMessage() {
        alert("You've been trolled!");
    }
    

    This works because the onunload event never fires when the user chooses to stay on the page.

提交回复
热议问题