0

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.

Rakesh Shetty
  • 4,548
  • 7
  • 40
  • 79
  • http://stackoverflow.com/questions/1119289/how-to-show-the-are-you-sure-you-want-to-navigate-away-from-this-page-when-ch – Guy P Apr 27 '13 at 10:23
  • Why do you want to show a message when the back button is pressed? – Quentin Apr 27 '13 at 10:25
  • @Quentin i have a some form type in my page if user click on back button without saving that form he should be alerted to save his form – Rakesh Shetty Apr 27 '13 at 10:31
  • You are on the right track. All you need now is to have your alert be conditional, only if something was changed in the form. Then, it will be ok if this alert also shows on "reload" as this will also cause the loss of data. – DannyB Apr 27 '13 at 10:33
  • But not if they click a link, type a different URL into the address bar or click a bookmark? Wouldn't it be more useful to show the warning all the time unless the form was being submitted? – Quentin Apr 27 '13 at 10:34
  • see my edited code i tried that code now please see if it help you guys – Rakesh Shetty Apr 27 '13 at 10:37

1 Answers1

0

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 (e.g. 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');
});
mv1
  • 558
  • 4
  • 8