In my Rails 3 application I do:
render :js => "alert(\"Error!\\nEmpty message sent.\");" if ...
Sometimes, below this error message (in the same alert box) I see: "Prevent this page from creating additional dialogs" and a checkbox.
What does this mean ?
Is that possible not to display this additional text and checkbox ?
I use Firefox 4.
It's a browser feature to stop websites that show annoying alert boxes over and over again.
As a web developer, you can't disable it.
What does this mean ?
This is a security measure on the browser's end to prevent a page from freezing the browser (or the current page) by showing modal (alert / confirm) messages in an infinite loop. See e.g. here for Firefox.
You can not turn this off. The only way around it is to use custom dialogs like JQuery UI's dialogs.
You can create a custom alert box using java script, below code will override default alert function
window.alert = function(message) { $(document.createElement('div'))
.attr({
title: 'Alert',
'class': 'alert'
})
.html(message)
.dialog({
buttons: {
OK: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).remove();
},
modal: true,
resizable: false,
width: 'auto'
});
};
Using JQuery UI's dialogs is not always a solution. As far as I know alert and confirm is the only way to stop the execution of a script at a certain point. As a workaround we can provide a mechanism to let the user know that an application needs to call alert and confirm. This can be done like this for example (where showError uses a jQuery dialog or some other means to communicate with the user):
var f_confirm;
function setConfirm() {
f_confirm = confirm;
confirm = function(s) {
try {
return f_confirm(s);
} catch(e) {
showError("Please do not check 'Prevent this page from creating additional dialogs'");
}
return false;
};
};
I designed this function to hopefully circumvent the checkbox in my web apps.
It blocks all functionality on the page while executing (assuming fewer than three seconds has passed since the user closed the last dialog), but I prefer it to a recursive or setTimeout function since I don't have to code for the possibility of something else being clicked or triggered while waiting for the dialog to appear.
I require it most when displaying errors/prompts/confirms on reports that are already contained within Modalbox. I could add a div for additional dialogs, but that just seems too messy and unnecessary if built-in dialogs can be used.
Note that this would probably break if dom.successive_dialog_time_limit is changed to a value greater than 3, nor do I know if Chrome has the the same default as Firefox. But at least it's an option.
Also, if anyone can improve upon it, please do!
// note that these should not be in the global namespace
var dlgRslt,
lastTimeDialogClosed = 0;
function dialog(msg) {
var defaultValue,
lenIsThree,
type;
while (lastTimeDialogClosed && new Date() - lastTimeDialogClosed < 3001) {
// timer
}
lenIsThree = 3 === arguments.length;
type = lenIsThree ? arguments[2] : (arguments[1] || alert);
defaultValue = lenIsThree && type === prompt ? arguments[1] : '';
// store result of confirm() or prompt()
dlgRslt = type(msg, defaultValue);
lastTimeDialogClosed = new Date();
}
usage:
dialog('This is an alert.');
dialog( 'This is a prompt', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'Is this a prompt?', 'maybe', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'OK/Cancel?', confirm );
if (dlgRslt) {
// code if true
}
This is a browser feature.
If you could, try to employ http://bootboxjs.com/, whit this library you can do the same of
alert("Empty message sent");
by writing:
bootbox.alert("Empty message sent", function(result) {
// do something whit result
});
You'll get a nice user interface too!
Related
I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload = handler
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
The closeIt() function:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
which also doesn't work - I cannot seem to bind to the beforeunload event.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
1) Use onbeforeunload, not onunload.
2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
This can't be done in chrome now to avoid spamming, refer to javascript onbeforeunload not showing custom message for more details.
Angular 9 approach:
constructor() {
window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {
if (this.generatedBarcodeIndex) {
event.preventDefault(); // for Firefox
event.returnValue = ''; // for Chrome
return '';
}
return false;
});
}
Browsers support and the removal of the custom message:
Chrome removed support for the custom message in ver 51 min
Opera removed support for the custom message in ver 38 min
Firefox removed support for the custom message in ver 44.0 min
Safari removed support for the custom message in ver 9.1 min
Try placing a return; instead of a message.. this is working most browsers for me.
(This only really prevents dialog's presents)
window.onbeforeunload = function(evt) {
//Your Extra Code
return;
}
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
This code called when user leave the page or close the active window and user logged out by 'logout.php'.
The new window close immediately when logout php consist of code:
window.close();
I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was :
1) It was giving message on all navigations I want it only for close click.
2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event; }
if (evt && evt.clientX >= (window.event.screenX - 150) &&
evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
refer from http://www.codeprojectdownload.com
What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.
$(window).one("beforeunload", BeforeUnload);
Try this
$(window).bind('beforeunload', function (event) {
setTimeout(function () {
var retVal = confirm("Do you want to continue ?");
if (retVal == true) {
alert("User wants to continue!");
return true;
}
else {
window.stop();
return false;
}
});
return;
});
I need to warn users about unsaved changes before they leave a page (a pretty common problem).
window.onbeforeunload = handler
This works but it raises a default dialog with an irritating standard message that wraps my own text. I need to either completely replace the standard message, so my text is clear, or (even better) replace the entire dialog with a modal dialog using jQuery.
So far I have failed and I haven't found anyone else who seems to have an answer. Is it even possible?
Javascript in my page:
<script type="text/javascript">
window.onbeforeunload = closeIt;
</script>
The closeIt() function:
function closeIt()
{
if (changes == "true" || files == "true")
{
return "Here you can append a custom message to the default dialog.";
}
}
Using jQuery and jqModal I have tried this kind of thing (using a custom confirm dialog):
$(window).beforeunload(function () {
confirm('new message: ' + this.href + ' !', this.href);
return false;
});
which also doesn't work - I cannot seem to bind to the beforeunload event.
You can't modify the default dialogue for onbeforeunload, so your best bet may be to work with it.
window.onbeforeunload = function() {
return 'You have unsaved changes!';
}
Here's a reference to this from Microsoft:
When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
The problem seems to be:
When onbeforeunload is called, it will take the return value of the handler as window.event.returnValue.
It will then parse the return value as a string (unless it is null).
Since false is parsed as a string, the dialogue box will fire, which will then pass an appropriate true/false.
The result is, there doesn't seem to be a way of assigning false to onbeforeunload to prevent it from the default dialogue.
Additional notes on jQuery:
Setting the event in jQuery may be problematic, as that allows other onbeforeunload events to occur as well. If you wish only for your unload event to occur I'd stick to plain ol' JavaScript for it.
jQuery doesn't have a shortcut for onbeforeunload so you'd have to use the generic bind syntax.
$(window).bind('beforeunload', function() {} );
Edit 09/04/2018: custom messages in onbeforeunload dialogs are deprecated since chrome-51 (cf: release note)
What worked for me, using jQuery and tested in IE8, Chrome and Firefox, is:
$(window).bind("beforeunload",function(event) {
if(hasChanged) return "You have unsaved changes";
});
It is important not to return anything if no prompt is required as there are differences between IE and other browser behaviours here.
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
1) Use onbeforeunload, not onunload.
2) The important thing is to avoid executing a return statement. I don't mean, by this, to avoid returning from your handler. You return all right, but you do it by ensuring that you reach the end of the function and DO NOT execute a return statement. Under these conditions the built-in standard dialog does not occur.
3) You can, if you use onbeforeunload, run an ajax call in your unbeforeunload handler to tidy up on the server, but it must be a synchronous one, and you have to wait for and handle the reply in your onbeforeunload handler (still respecting condition (2) above). I do this and it works fine. If you do a synchronous ajax call, everything is held up until the response comes back. If you do an asynchronous one, thinking that you don't care about the reply from the server, the page unload continues and your ajax call is aborted by this process - including a remote script if it's running.
This can't be done in chrome now to avoid spamming, refer to javascript onbeforeunload not showing custom message for more details.
Angular 9 approach:
constructor() {
window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {
if (this.generatedBarcodeIndex) {
event.preventDefault(); // for Firefox
event.returnValue = ''; // for Chrome
return '';
}
return false;
});
}
Browsers support and the removal of the custom message:
Chrome removed support for the custom message in ver 51 min
Opera removed support for the custom message in ver 38 min
Firefox removed support for the custom message in ver 44.0 min
Safari removed support for the custom message in ver 9.1 min
Try placing a return; instead of a message.. this is working most browsers for me.
(This only really prevents dialog's presents)
window.onbeforeunload = function(evt) {
//Your Extra Code
return;
}
You can detect which button (ok or cancel) pressed by user, because the onunload function called only when the user choise leaveing the page. Althoug in this funcion the possibilities is limited, because the DOM is being collapsed. You can run javascript, but the ajax POST doesn't do anything therefore you can't use this methode for automatic logout. But there is a solution for that. The window.open('logout.php') executed in the onunload funcion, so the user will logged out with a new window opening.
function onunload = (){
window.open('logout.php');
}
This code called when user leave the page or close the active window and user logged out by 'logout.php'.
The new window close immediately when logout php consist of code:
window.close();
I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was :
1) It was giving message on all navigations I want it only for close click.
2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.
Following is the solutions code I found, which I wrote on my Master page.
function closeMe(evt) {
if (typeof evt == 'undefined') {
evt = window.event; }
if (evt && evt.clientX >= (window.event.screenX - 150) &&
evt.clientY >= -150 && evt.clientY <= 0) {
return "Do you want to log out of your current session?";
}
}
window.onbeforeunload = closeMe;
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
</script>
refer from http://www.codeprojectdownload.com
What about to use the specialized version of the "bind" command "one". Once the event handler executes the first time, it’s automatically removed as an event handler.
$(window).one("beforeunload", BeforeUnload);
Try this
$(window).bind('beforeunload', function (event) {
setTimeout(function () {
var retVal = confirm("Do you want to continue ?");
if (retVal == true) {
alert("User wants to continue!");
return true;
}
else {
window.stop();
return false;
}
});
return;
});
I used to display my validation as well as success/failure messages through alert pop-ups but now my requirement is to display the same using HTML label texts and make them disappear after a particular amount of time. I am currently using a timeout function:
if ($("#lblErrorMessage").text() != "") {
clrMsg = setTimeout(function(e) {
$("#lblErrorMessage").text("");
clearTimeout(clrMsg);
}, 5000);
}
This approach is very messy and there is no way to check whether the message is success (needs to be displayed for longer) or error/failure message (needs to be displayed for shorter period). Can anyone suggest a function which can be used throughout the page and also meet the requirements I want?
Thanks in advance
With an added class?
You don't show how you add the message in #lblErrorMessage...
But I suppose you can also add a class to it like "success" or "fail".
$("#lblErrorMessage").text("Some success messsage to user.").addClass("success");
removeMessage();
or
$("#lblErrorMessage").text("Some error messsage to user.").addClass("fail");
removeMessage();
Then, here is the new setTimeout function:
function removeMessage(){
if ($("#lblErrorMessage").text() != "") {
if $("#lblErrorMessage").hasClass("success"){
clrDelay = 5000;
}
else if $("#lblErrorMessage").hasClass("fail"){
clrDelay = 2500;
}
clrMsg = setTimeout(function(e) {
$("#lblErrorMessage").text("");
//clearTimeout(clrMsg); // No use for that.
$("#lblErrorMessage").removeClass("success fail"); // Remove classes for future messages.
}, clrDelay);
}
}
In my Rails 3 application I do:
render :js => "alert(\"Error!\\nEmpty message sent.\");" if ...
Sometimes, below this error message (in the same alert box) I see: "Prevent this page from creating additional dialogs" and a checkbox.
What does this mean ?
Is that possible not to display this additional text and checkbox ?
I use Firefox 4.
It's a browser feature to stop websites that show annoying alert boxes over and over again.
As a web developer, you can't disable it.
What does this mean ?
This is a security measure on the browser's end to prevent a page from freezing the browser (or the current page) by showing modal (alert / confirm) messages in an infinite loop. See e.g. here for Firefox.
You can not turn this off. The only way around it is to use custom dialogs like JQuery UI's dialogs.
You can create a custom alert box using java script, below code will override default alert function
window.alert = function(message) { $(document.createElement('div'))
.attr({
title: 'Alert',
'class': 'alert'
})
.html(message)
.dialog({
buttons: {
OK: function() {
$(this).dialog('close');
}
},
close: function() {
$(this).remove();
},
modal: true,
resizable: false,
width: 'auto'
});
};
Using JQuery UI's dialogs is not always a solution. As far as I know alert and confirm is the only way to stop the execution of a script at a certain point. As a workaround we can provide a mechanism to let the user know that an application needs to call alert and confirm. This can be done like this for example (where showError uses a jQuery dialog or some other means to communicate with the user):
var f_confirm;
function setConfirm() {
f_confirm = confirm;
confirm = function(s) {
try {
return f_confirm(s);
} catch(e) {
showError("Please do not check 'Prevent this page from creating additional dialogs'");
}
return false;
};
};
I designed this function to hopefully circumvent the checkbox in my web apps.
It blocks all functionality on the page while executing (assuming fewer than three seconds has passed since the user closed the last dialog), but I prefer it to a recursive or setTimeout function since I don't have to code for the possibility of something else being clicked or triggered while waiting for the dialog to appear.
I require it most when displaying errors/prompts/confirms on reports that are already contained within Modalbox. I could add a div for additional dialogs, but that just seems too messy and unnecessary if built-in dialogs can be used.
Note that this would probably break if dom.successive_dialog_time_limit is changed to a value greater than 3, nor do I know if Chrome has the the same default as Firefox. But at least it's an option.
Also, if anyone can improve upon it, please do!
// note that these should not be in the global namespace
var dlgRslt,
lastTimeDialogClosed = 0;
function dialog(msg) {
var defaultValue,
lenIsThree,
type;
while (lastTimeDialogClosed && new Date() - lastTimeDialogClosed < 3001) {
// timer
}
lenIsThree = 3 === arguments.length;
type = lenIsThree ? arguments[2] : (arguments[1] || alert);
defaultValue = lenIsThree && type === prompt ? arguments[1] : '';
// store result of confirm() or prompt()
dlgRslt = type(msg, defaultValue);
lastTimeDialogClosed = new Date();
}
usage:
dialog('This is an alert.');
dialog( 'This is a prompt', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'Is this a prompt?', 'maybe', prompt );
dialog('You entered ' + dlgRslt);
dialog( 'OK/Cancel?', confirm );
if (dlgRslt) {
// code if true
}
This is a browser feature.
If you could, try to employ http://bootboxjs.com/, whit this library you can do the same of
alert("Empty message sent");
by writing:
bootbox.alert("Empty message sent", function(result) {
// do something whit result
});
You'll get a nice user interface too!
Hello Seniors (As I am new to Web Based Applications),
I was keen to implement or catching browser closing event.
Yes! I did it and successfully implemented it by using javascript{see code below}
but I have implemented it in a web page without MasterPage.
Now, as I am trying to implement it in a webpage with MASTERPAGE but in each post back...the event window.onunload is caught, which is giving me problems...
Is there any technique or logic to detect whether I can differentiate between a Close browser button and a page's post back event.
Please guide me...as I have to implement in a project as soon as possible....
thank you.
Ankit Srivastava
<script type="text/javascript">
function callAjax(webUrl, queryString)
{
var xmlHttpObject = null;
try
{
// Firefox, Opera 8.0+, Safari...
xmlHttpObject = new XMLHttpRequest();
}
catch(ex)
{
// Internet Explorer...
try
{
xmlHttpObject = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(ex)
{
xmlHttpObject = new ActiveXObject('Microsoft.XMLHTTP');
}
}
if ( xmlHttpObject == null )
{
window.alert('AJAX is not available in this browser');
return;
}
xmlHttpObject.open("GET", webUrl + queryString, false);
xmlHttpObject.send();
return xmlText;
}
</script>
<script type="text/javascript">
var g_isPostBack = false;
window.onbeforeunload = check ()
function check()
{
if ( g_isPostBack == true )
return;
var closeMessage =
'You are exiting this page.\n' +
'If you have made changes without saving, your changes will be lost.\n' +
'Are you sure that you want to exit?';
if ( window.event )
{
// IE only...
window.event.returnValue = closeMessage;
}
else
{
// Other browsers...
return closeMessage;
}
g_isPostBack = false;
}
window.onunload = function ()
{
if ( g_isPostBack == true )
return;
var webUrl = 'LogOff.aspx';
var queryString = '?LogoffDatabase=Y&UserID=' + '<%# Session["loginId"] %>';
var returnCode = callAjax(webUrl, queryString);
}
</script>
There is no javascript event which differentiates between a browser being closed and the user navigating to another page (either via the back/forward button, or clicking a link, or any other navigation method). You can only tell when the current page is being unloaded. Having said that, I'm not sure why you'd even need to know the difference? Sounds like an XY problem to me.
The answer can be found on SO:
How to capture the browser window close event?
jQuery(window).bind("beforeunload", function(){return confirm("Do you really want to close?") })
and to prevent from confirming on submits:
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
First step: add global JavaScript variable called "_buttonClicked" which is initially set to false.
Second step: have every button click assign _buttonClicked value to true.. with jQuery it's one line, pure JavaScript is also few lines only.
Third step: in your function check _buttonClicked and if it's true, don't do anything.
EDIT: After quick look in your code I see you already have steps #1 and #3, so all you need is the second step, assign g_isPostBack as true when any submit button is clicked. Let me know if you need help implementing the code and if you can have jQuery.
If one wants to catch Log out when the browser is closed (by clicking on the cross), we can take the help of window events.
Two events will be helpful: onunload and onbeforeunload.
But the problem arises that the code will also work if you are navigating from one page to another as well as also when one
refreshes the page. We don't want our sessions to be clear and inserting the record of logging out while refreshing.
So the solution is if we distinguish the difference between closing and refreshing or navigating.
I got the solution:
Write 'onbeforeunload ="loadOut();"' within the body tag on master page.
Add the following function inside script in head section of master page :-
function loadOut() {
if ((window.event.clientX < 0) || (window.event.clientY < 0))
{
// calling the code behind method for inserting the log out into database
}
}
And its done. It is working for IE, please check for other browsers. Similarly you can detect the event if the window is closed
by pressing the combination of keys ALT+F4.
window.unload fires when we navigate from one page to another as well as when we click on close button of our browser,So to detect only browser close button you need to use flag.
var inFormOrLink;
$("a,:button,:submit").click(function () { inFormOrLink = true; });
$(":text").keydown(function (e) {
if (e.keyCode == 13) {
inFormOrLink = true;
}
})/// Sometime we submit form on pressing enter
$(window).bind("unload", function () {
if (!inFormOrLink) {
$.ajax({
type: 'POST',
async: false,
url: '/Account/Update/'
});
}
})