Intercept selection in window.onbeforeunload dialog - javascript

in my web application if the user leaves the current page without having saved changes in the form a pop up window is opened to alert him about that.
For the pop up I use some scripts code injected from codebehind (C#):
var Confirm = true;
window.onbeforeunload = confirmClose;
function confirmClose()
{
if (!Confirm) return;
if(/*CHECK CHANGE CONDITION IS TRUE*/)
{ return " + WARN_message + "; }
}
I would need to intercept whether the user click on cancel or ok button.
I tried like:
var button_pressed = window.onbeforeunload = confirmClose;
But it returns always true.
How can get which button was pressed?
Thanks

Not possible. There is no event associated with the buttons.
What you might be able to do was to see if the user came back by setting a value or perhaps a cookie in the page in the onbeforeunload and test if it is there after some time has passed
but see the duplicate Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

Related

Prevent browser back button navigation without page focus or touch

Without clicking/touching on anywhere inside page when click browser back button, navigation should be disable.
Below implementation only work when click inside page.
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () =>{ // not getting activate without clicking inside page
console.warn('DISABLE BROWSER NAVIGATION');
history.forward();
}
one of the best way is to open your application in a popup without controls but again depending upon your requirement this may not be applicable. Hope this helps. Something like below
function openPopup(){
var pathname = (window.location.pathname);
window.open(pathname+'openpagePopup.html','','width=800,height=450,toolbar=no, menubar=no,scrollbars=no,resizable=no,dependent,screenx=80,screeny=80,left=80,top=20,scrollbars=no');
return false;
}
The otherways are not trustworthy like you can show user an alert, but can not disable the back button, as per my knowledge. If you do the below make sure you check browser compatibility.
window.onbeforeunload = function() {
return "Write something here";
};
Update : I found there is a way to handle the page history. Incase that works, I have never tried, here is a link
JS - window.history - Delete a state

window return value when closing modal with the X button

I am developing a web application that our client calls with something like:
var result = window.showModalDialog('http://example.com/myapp','My webapp', 'dialogtop=0;dialogleft=0;dialogwidth:' + (window.screen.width - 200) + ';dialogheight:' + (window.screen.height - 200) + ';status=no;resizable=yes;scroll=yes;maximize:yes;minimize:no;' );
and when they close this modal dialog, they capture what we have returned.
We load our response in window.returnValue so they have it in the "result" variable, but if they close our window with the X button, they never get our response, although we have set it. If they close our window by clicking on our "Accept" button, they get the response.
If I try to capture the unload event, and I set window.returnValue again, they don't get it either.
Why is this happening and how can I make sure they get the return value even they press the X?
I can't change how they call our web application, which I know it sucks because it's a dumb way to do things...
They use Internet Explorer exclusively and they run it in mode IE 5...
If possible for you then you can try to make a test with the onbeforeunload event
In that way, you can try to show the prompt to the users and inform them that if they continue with this approach them they can lose the changes they have made on this page. Then you can guide the user with correct steps.
Example:
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Accept button, your changes will be lost. Are you sure you want to exit this page?";
}

How can I warn user on back button click?

www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.

How to capture when a user is leaving ASP.Net page unexpectedly

I need to prompt a user when they are leaving my ASP.Net page unexpectedly with a message to ask if they are sure they want to leave. A post back or when the save button is clicked should not fire the warning. There are a bunch of articles covering this but I am brand new to this and appear to have got my wires crossed.
The recommended way appears to be to use the window.onbeforeunload event but behaves unexpectedly for me. This is fired when the page loads as opposed to when the page unloads.
<script language="JavaScript" type="text/javascript">
window.onbeforeunload = confirmExit;
function confirmExit() {
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
If I use the JQuery implementation it fires when the page unloads but the problem is it fires before the code behind is executed. So I cannot set a variable on the client saying don’t fire the event this time as it is a post back or a Save.
$(window).bind('beforeunload', function () {
return 'Are you sure you want to leave?';
});
Can anyone point me in the correct direction as I know I am making basic mistakes/miss-understanding?
Edit:
So I am nearly there:
var prompt = true;
$('a').live('click', function () {
//if click does not require a prompt set to false
prompt = false;
});
$(window).bind("beforeunload", function () {
if (prompt) {
//reset our prompt variable
prompt = false;
//prompt
return true;
}
})
Except the problem is in the above code I need to be able to differentiate between the clicks but I haven't been able to figure that out yet i.e. I am missing a condition here "//if click does not require a prompt set to false".
Any ideas?
Thanks,
Michael
You can try using this:
$(window).unload(function(){
alert('Message');
});
In case people are interested this is the roundabout solution to my problem. How to tell if a page unload in ASP is a PostBack

Silverlight 4: OnBeforeUnload

I have a silverlight application and I want to capture the close event of the browser. So what I did, in my .aspx page i have this code
function closeIt() {
return "Any string value here forces a dialog box to \n" +
"appear before closing the window.";
}
window.onbeforeunload = closeIt;
If this functions triggered, a popupwindow will appear, you have 2 buttons OK and CANCEL.
Is there a way in silverlight or in server side to get the value of what the user clicks?
Thank you
I am not sure I totally understand your question, it looks like you are writing javascript. But your subject is silverlight. Anyway....
The simplest way is to leverage Html Confirm either in silverlight:
bool result = System.Windows.Browser.HtmlPage.Window.Confirm("Really..?");
or in straight JavaScript:
var result = window.Confirm("Really...?");
To get the value to the server you can store the value in a hidden text field and post it to the server.
Why don't you use MessageBox ? here's code example:
MessageBoxResult result = MessageBox.Show("Text","Title",MessageBoxButton.OKCancel);
if (MessageBoxResult.OK==result)
{
}
else if (result == MessageBoxResult.No)
{
}
this will get you a popup window with OK and CANCEL window with pretty easy way to determine whether user clicked Ok or no.
The answer is pretty much the same as my other answer to your prior question re window.close.
When the user selects Cancel absolutely nothing happens. If they select OK then your Application_Exit will run.

Categories

Resources