AngularJS how to show browser dialog protects before changing tab - javascript

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.
Thanks in advance :)

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

Related

window.onbeforeunload not working properly after postback/page load

I've got this simple function that prevents users to accidentally close browser pages (in my case on chrome) prompting a confirmation message.
window.onbeforeunload = function () {
return "Are you sure you want to leave this page?";
};
It works all fine but i found some limitations:
on page load the function doesn't work if you first don't interact with the page in some way
e.g. click somewhere in the DOM
This behavior is particularly annoying inside the classic asp net application (web page) that loads data from a DB into a gridview because every time data is loaded the postback appends and if you close the tab no confirmation message appears. (i know you can use UpdatePanels to avoid the postback, but it's not the solution i'm looking for)
I tried to generate a click on some element of the DOM on page load:
$('#someID').click();
but didn't work.
Any ideas?
According to https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload :
You can and should handle this event through window.addEventListener()
and the beforeunload event. More documentation is available there.
The linked articles go on to state:
WebKit-based browsers don't follow the spec for the dialog box. An
almost cross-browser working example would be close to the following:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
e.returnValue = confirmationMessage; // Gecko, Trident, Chrome 34+
return confirmationMessage; // Gecko, WebKit, Chrome <34
});
try using $('#someID').focus() instead of $('#someID').click().
$(document).ready(function () {
$('#someID').focus();
});

Confirmation on close or refresh page not working at all

When the user closes the tab or refreshes the page, the site must display a popup to confirm this.
I tried this code:
window.onbeforeunload = function (e) {
return confirm("Are you sure you want to leave this page?");
};
This didn't work in either firefox or chrome.
In firefox no popup came up. And in chrome the default one didn't get overridden either.
I even tried using the following code but to no avail:
window.onbeforeunload = function (e) {
var dialogText = 'Are you sure about this?';
e.returnValue = dialogText;
return dialogText;
};
How do I solve this issue?
Any code snippets would be helpful. Thank you.
I found this snippet on the internet:
window.onbeforeunload = function (e) {
return "Please click 'Stay on this Page' if you did this unintentionally";
};
This is working perfectly as required.
I found out that you actually don't need to add any confirm call. If you just return a string, this will prompt the browser to confirm leaving the page. Most commercial browsers have this functionality supported by default.
From Firefox's documentation:
To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with.
You cannot show pop-up if user didn't interacted with the page before.
Starting with Firefox 4, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."
-- from Mozilla Developer Docs

Alert Before Page Close: How to change the Chrome's default message?

I am using the following code snippet to trigger an alert before page closes but Chrome seems to ignore the message and displays its default message "Do you want to leave this site? Changes you made might not be saved". How can I make chrome show my message instead of the default one?
window.onbeforeunload = function(e) {
e.returnValue = "A search is in progress, do you really want to stop the search and close the tab?";
return "A search is in progress, do you really want to stop the search and close the tab?";
}
I only recently realized that Chrome had changed the behavior of onbeforeunload. I found a workaround that works for the main browsers (tested in Chrome, Firefox and IE, the jsFiddle for some reason doesn't work in Firefox, but my website does). Using jQuery UI, you can make a dialog window come up when leaving the page that gives more info about why leaving the current page would be a problem.
window.onbeforeunload = function (e) {
$('<div title="Warning!">A search is in progress, do you really want to stop the search and close the tab? If not, choose "Stay on page" on the browser alert.</div>').dialog({
modal:true,
close: function(){$(this).dialog('destroy').remove();}
});
return "Random message to trigger the browser's native alert.";
}
jsFiddle here
Update: Deprecated in Chrome : https://developers.google.com/web/updates/2016/04/chrome-51-deprecations?hl=en
Try the following:
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'A search is in progress, do you really want to stop the search and close the tab?';
}
// For Safari
return 'A search is in progress, do you really want to stop the search and close the tab?';
};
Message I get in Chrome (both custom and default):
A search is in progress, do you really want to stop the search and
close the tab?
Are you sure you want to leave this page?
Source jsFiddle

Is it possible to fire a modal when the user attempts to close the browser with AngularJS?

like says my title...
Is it possible to fire a modal when the user attempts to close the browser with AngularJS? I need to show the modal for the user to fill out a survey.
If that is possible, have u some tuto? I have trying the next code in my controller, but displays a confirm window.
$window.onbeforeunload = function (event) {
var message = 'If you leave this page you are going to lose all unsaved changes, are you sure you want to leave?';
if (typeof event == 'undefined') {
event = $window.event;
}
return message;
};
Thanks for ur help.
beforeunload is a browser standard. Whatever you return from the function is the message that displays in the confirmation dialog before closing the window.
If you're using a browser that complies to this standard like Firefox, Chrome, or IE, you won't be able to hijack the native behaviour. So, your confirmation message should be persuasive enough for the user to want to stay on your site.

How to detect the window(new tab) close event?

I have one parent page and child page. the child page opened in new tab
I want to show one alert message (The child page is closing), when i close the child tab.
How to show the closing messgae, when close the tab? (Not refreshing time)
I used onunload, and onbeforeunload.
Two methods are also called, when the page refresh and tab closing.
window.onunload = function doUnload(e)
{
alert('Child window is closing...');
}
and
window.onbeforeunload = function doUnload(e)
{
alert('Child window is closing...');
}
I must show the alert message, only close the tab in browser.
Help me.
Thanks in advance.
Update
I use the following script. Its worked In IE. But not worked in FireFox
<script language="javascript" type="text/javascript">
window.onbeforeunload = function()
{
if ((window.event.clientX < 0) || (window.event.clientY < 0) || (window.event.clientX < -80))
{
alert("Child window is closing...");
}
};
</script>
How to acheive this in FireFox and other Browser.
There is afaik never been a cross browser script for this. The solution is to NOT rely on undocumented and changeable features of a specific browser to detect something that is important.
Since you have a CHILD page, you can set up a test in the parent (opener) that at intervals test the childWindowHandle.closed property and acts on that.
Does the script from http://chrismckee.co.uk/good-sir-before-you-unload-crossbrowser-javascript-headaches/ work?
Assuming your just trying to fire beforeunload event crossbrowser, this pretty much does it ( excluding opera )
try{
// http://www.opera.com/support/kb/view/827/
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}catch(e){}
//Our Where The F' Are You Going Message
function ReturnMessage()
{
return "WTF!!!";
}
//UnBind Function
function UnBindWindow()
{
window.onbeforeunload = null;
return true;
}
//Bind Links we dont want to affect
document.getElementById('homebtn').onclick = UnBindWindow;
document.getElementById('googlebtn').onclick = UnBindWindow;
//Bind Exit Message Dialogue
window.onbeforeunload = ReturnMessage;
There is an example in Mozilla Devloper site which basically says check for browser type
and use the below check accordingly.Hope this helps.
You might not be able to do that other than some cookie based methods which is development work arounds like non persistent cookies. Second identifying a page refresh, form based redirect, or back redirect or browser close unload event identification is not direct and is tedious. Recommend not to depend on it.
you can do some small things before the customer closes the tab. javascript detect browser close tab/close browser but if your list of actions are big and the tab closes before it is finished you are helpless. You can try it but with my experience donot depend on it. Yes, you cannot at this time differentiate back and refresh and close. So no foolproof way of saying whether the child has definitely closed.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
/* Do you small action code here */
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

Categories

Resources