Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is Facebook handling their onbeforeunload confirmation dialog?

When browsing Facebook in the latest Chrome on OSX, I noticed that beginning to type in a comment box and clicking another link or pressing the back button triggers a confirmation window asking if I'd like to leave:

Facebook Confirmation Dialog

Being an old school developer, I had believed that the only possibility was to attach an onbeforeunload event to the page to handle the back button click. I know you can do a global binding on the anchors to simulate onbeforeunload, but I was surprised they managed to have a custom styled confirmation and not the stock, ugly looking confirmation dialog.

How did they do it? Is this some kind of HTML5 window history or pushState event trigger?

like image 269
Corey Ballou Avatar asked Feb 04 '14 15:02

Corey Ballou


1 Answers

Ok, I found this answer on Stackoverflow here.

This handles the onbeforeunload.
To test this in your browser simply put

window.onbeforeunload = function() { return "Your work will be lost."; };

into your console, press enter and try the back button.

Now for your real answer:

Facebook handles the pressing of the back button in the above described way (as I tested out) and the cancel(l)ing of a comment by clicking on another link on the page with the div that pops up in your question.

Edit

If it would be possible to prevent the browser from leaving the AJAX context, this would work (add it in the console):

window.onpopstate = function (event) {
 alert("location: " + document.location);
 event.preventDefault();
 return false;
}

I answered here since facebook does not do it, which was your initial question. But I sincerely hope someone proves it wrong!

like image 197
loveNoHate Avatar answered Oct 24 '22 13:10

loveNoHate