Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

beforeunload oddities

The problem

Using $(window).bind("beforeunload", ...[snip] to ask if a user wishes to leave the page yields some strange results in some browsers. The dialogue pops up and asks if you wish to stay on the page or leave the page. If you click the stay on the page option, Google Chrome (latest - 13.0.782.215 m) and WinIE7 pops the last history page in the "Back" button.

To illustrate this point, current session history consists of visiting the following pages:

  • Page 3
  • Page 2
  • Page 1

You decide to leave Page 3 and the beforeunload event fires. You choose to stay on the current page.

You click the back button again and this time decide to leave the page. You should find yourself at Page 2, but instead you are at Page 1. You can navigate again forward to Page 2 though.

The question

How can I prevent the browser from removing these pages from the back button when we choose the "stay on current page" option? Is it possible?

Example of the problem

Using Google Chrome, in a new window, head to http://stackoverflow.com and browse a few questions without going back. Then hit the Ask Question button. Begin typing in the dialogue box. Press Back in your browser. Select stay on page. Press back in browser again and this time select the leave page option. You have now gone back two pages in history. You can essentially go back multiple pages if you click stay on page more than once.

Why does this matter?!

I don't want to confuse my users. They are not the computer-savvy type.

My code (not that it is relevant)

$(window).bind("beforeunload", function(){
    if (in_edit > 0){
        return "You are currently editing this job.\n\nAre you sure you wish to exit the page?";
    }
});
like image 828
dan Avatar asked Aug 23 '11 04:08

dan


People also ask

What triggers Beforeunload?

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. This event enables a web page to trigger a confirmation dialog asking the user if they really want to leave the page.

What is Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

Is it possible to display a custom message in the Beforeunload popup?

You can't set a custom message on a modern browser instead you can use of default alert function. Save this answer. Show activity on this post. Save this answer.


1 Answers

Chromium resolved the issue in 2012: You can view the details here: https://code.google.com/p/chromium/issues/detail?id=93858

like image 74
dan Avatar answered Oct 23 '22 22:10

dan