Alerts when navigating away from a web page

JavascriptBrowserGoogle DocsAlerts

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVijay DevView Question on Stackoverflow
Solution 1 - JavascriptPeter BaileyView Answer on Stackoverflow
Solution 2 - JavascriptmcandreView Answer on Stackoverflow