Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alerts when navigating away from a web page

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?

like image 552
Vijay Dev Avatar asked Aug 17 '09 17:08

Vijay Dev


People also ask

How do I stop navigate from a page?

To prevent a webpage from navigating away using JavaScript, we can set the window. onbeforeunload property to a function that returns any value. window. onbeforeunload = () => { return ""; };

How do I prompt unsaved data before leaving site?

One solution is to use the beforeunload event in combination with a "dirty" flag, which only triggers the prompt if it's really relevant. var isDirty = function() { return false; } window.

What is window Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

What is navigating away?

vb. 1 to plan, direct, or plot the path or position of (a ship, an aircraft, etc.) 2 tr to travel over, through, or on (water, air, or land) in a boat, aircraft, etc. 3 Informal to direct (oneself, one's way, etc.) carefully or safely.


1 Answers

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); 
like image 162
Peter Bailey Avatar answered Oct 03 '22 21:10

Peter Bailey