55

When I try to close my Google docs tab with unsaved changes, this is what I get in my browser (FF 3.5).

Are you sure you want to navigate away from this page?

You have unsaved changes in this document. Click Cancel now, then 'Save' to save them. Click OK now to discard them.

Press OK to continue, or Cancel to stay on the current page.

My question is whether such alerts are part of the web app (gdocs for eg.) or are they given out by the browser? If latter, how is this done?

2 Answers 2

86

By the browser. It's the beforeunload event handler that returns the customized text of the dialog, which is only the middle of the three paragraphs - the other two paragraphs as well as the text of the buttons cannot be customized or otherwise changed.

window.onbeforeunload = function(){ return 'Testing...' }

// OR

var unloadListener = function(){ return 'Testing...' };
window.addEventListener('beforeunload', unloadListener);

Will yield a dialog that says

Are you sure you want to navigate away from this page?

Testing...

Press OK to continue, or Cancel to stay on the current page.

You can nullify this by setting the handler to null

window.onbeforeunload = null;

// OR

window.removeEventListener('beforeunload', unloadListener);
5
  • Thanks Peter. I have looked into how the modern browsers behave wrt the onbeforeunload event and posted my findings. Please add on any other intricate details that you know.
    – Vijay Dev
    Aug 21, 2009 at 17:39
  • Hi Peter, is there no way we can tap into the event to yield a custom alert which provides the same functionality as the native window alert?
    – SexyBeast
    Sep 10, 2013 at 19:51
  • Not that I know of, no. Sep 10, 2013 at 21:48
  • 1
    @PeterBailey I suggest you updating your answer and use more modern addEventListener instead of onbeforeunload. Also, the event name is beforeunload, not onbeforeunload. Dec 31, 2015 at 9:19
  • @MichałPerłakowski, it seems that another answer is warranted (with your suggestions).
    – isherwood
    Sep 16, 2017 at 14:28
-16

The alerts are part of the web application. View the source code and look at the javascript.

3
  • I cannot see it in Google Docs source, at least.
    – Vijay Dev
    Aug 17, 2009 at 17:22
  • It's likely buried in some obscure JavaScript file. Google uses scripts that make their JavaScript files essentially unreadable to a human.
    – ceejayoz
    Aug 17, 2009 at 17:31
  • before using alert, an event has to identified first. which "onBeforeUnload" Jan 20, 2015 at 6:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.