Ellbar Ellbar - 2 years ago 99
AngularJS Question

AngularJS how to show browser dialog protects before changing tab

I have to display a message which warns the user before changing tab without saving changes. An url in the browser does not change in this process because user changes only a tab.

SetPristine, SetDirty will not help me because the url does not change. Is there any way to display this system-browser popup manually? If not maybe can you tell me how to create identical alert in the same space (it is placed in top-center part of the website).

I would like to get a result similar to the picture below.

enter image description here

Thanks in advance :)

Answer Source

What your asking for is not an Angular only thing. You can do it in pure javascript.

What you're asking about is the beforeUnload event.

Here is some sample code from mozilla:

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
  return confirmationMessage;              // Gecko, WebKit, Chrome <34

This example prevents a dialog box, but to show one you need to set the return value to your dialog text:

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  return "You will loose any unsaved changes, by leaving the page"

Another mozilla page explains in more detail

What this means is you can put other code in the event handler that will pop up a modal say, or some other dialog to inform the user about data loss.

If what you want is actually about changing tab, then the cleanest way is to use the Page Visibility API which is reasonably well supported now.

What you want is now more like so:

document.addEventListener("visibilitychange", handleVisibilityChange, false);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download