简体   繁体   中英

Show alert message on browser back button but dont show alert on refresh

I want to show a alert box when user click on browser back button. I found this but it shows on reload ..

$(window).bind("beforeunload", function() {
    return "HI";
});

Edited :-

now I tried this one it shows alert box on back button but it also shows on refresh I dont want that.Code is :-

var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++)
{
    links[i].onclick = setGlobal;
}
function setGlobal()
 {
    window.linkClicked = true;
 }
window.onbeforeunload = function()
{
    if (typeof window.linkClicked == 'undefined' || !window.linkClicked)
    {
        return "Are you sure?"
    }
}

It shows the alert box even when I come to this page i dont want that I want if user click on back button if he is on this page.

Please Im new to this any help will be appreciated .Thanks in advance.

Here is an idea (it seems you are already using jQuery).

Firstly, you need to capture the "beforeunload" event (which you did):

// Display browser warning message when back/forward/reload or hyperlink navigation occurs
$(window).on('beforeunload', function(e) {
  console.log('page navigation captured');
  return 'By leaving this page you will lose the data you have entered here.';
});

Secondly, you need to allow non-disrupted navigation from certain elements (eg all elements with class="allow-navigation"):

// Disable capture for certain elements
$('.allow-navigation').on('click', function(e) {
    $(window).off('beforeunload');
    console.log('page navigation allowed');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM