2

Possible Duplicates:
How can I ask a web user for confirmation if he really wants to leave the page?
Client/JS Framework for “Unsaved Data” Protection?

Like stackoverflow does on the ask page, when I click the close button or any other link on the site a dialog pops up asking if you're sure you want to navigate away from the page. How to do that in javascript or jQuery and can you customize the text in the box?

Community
  • 1
  • 1
Kaley
  • 23
  • 1
  • 3

1 Answers1

9

You want to listen to the onbeforeunload event:

window.onbeforeunload = function (e) {
  return 'Are you sure?';
};

https://developer.mozilla.org/en/DOM/window.onbeforeunload

William Niu
  • 15,798
  • 7
  • 53
  • 93
  • this is exactly what I was looking for, just one thing though. The custom text "are you sure" appears in between the default browsers message "Are you sure you want to navigate away from this page..." and "Press ok to continue or cancel to stay on the current page...". Is there a way to remove the default text and have just the custom? – Kaley Mar 19 '11 at 23:09
  • Not I know off....that was what I wanted to do as well, but couldn't find a way to. – William Niu Mar 19 '11 at 23:39
  • No, that would be insecure, as you wouldn't realise it was the web page prompting you not to leave the page, rather than the browser. – Neil Mar 19 '11 at 23:57
  • A bit late, but still: anyone found a way to remove default browsers text there? – trainoasis Dec 15 '14 at 14:46