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:
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?
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With