Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

javascript - How to control browser confirmation dialog on leaving page?

I know there are a lot of questions regarding this but nothing is answering me right. I want to show a confirmation dialog when user leaves the page. If the user press Cancel he will stay on page and if OK the changes that he has made will be rollback-ed by calling a method. I have done like this:

window.onbeforeunload = function () {
  var r = confirm( "Do you want to leave?" );
  if (r == true) {
       //I will call my method
  }
  else {
      return false;
  }
};

The problem is that I am getting the browser default popup: "LeavePage / StayOnPage"

This page is asking you to confirm that you want to leave - data you have entered may not be saved.

This message is shown in Firefox, in Chrome is a little different. I get this popup after I press OK on my first confirmation dialog.

Is there a way not to show this dialog? (the second one, that I did not create). Or if there is any way to control this popup, does anyone know how to do that? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's what I've done, modify to fit your needs:

// This default onbeforeunload event
window.onbeforeunload = function(){
    return "Do you want to leave?"
}

// A jQuery event (I think), which is triggered after "onbeforeunload"
$(window).unload(function(){
    //I will call my method
});

Note: it's tested to work in Google Chrome, IE8 and IE10.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...