How to handle browser close event through Java script - javascript

I have an application which logs users session once he logins. Say i have view case page and when user click a case it would be locked by that user and the action is tracked by inserting an entry into lock table with the java Session, caseid and userId. Now when the user click any other tab within the application, including logout an action is called to delete the session id in the lock table for that user and case. I have a requirement to release this lock even when the user closes the browser close button. My backend code will handle the scenario when the elapsedTime of the lock is greater than 10mins. However when the user closes the browser and some other user logins to view the same case within this span of 10mins it still shows the lock by the previous user. So i have to catpure the browser close event and do the same action as i do for logout and other tab click. My below piexe of java script code works well in IE browser for browser close but doesnt work in chrome or firefox. Can someone suggest which event to use in chrome/firefox please?
<script type="text/javascript">
document.getElementById('logoff').onclick = function(){
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
};
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
$("input[type=button]").bind("click", function() {
validNavigation = true;
});
window.onbeforeunload = function() {
if (!validNavigation) {
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
}
};
});
</script>

It seems like using the onbeforeunload property is discouraged:
Typically, it is better to use window.addEventListener() and the beforeunload event, instead of onbeforeunload.
It should look like this:
window.addEventListener('beforeunload', function (e) {
// the absence of a returnValue property on the event will guarantee the browser unload happens
delete e['returnValue'];
if (!validNavigation) {
sessionStorage.setItem('accept', '0');
location.href="/abc/logout/";
}
});

Related

Remove page refresh browser popup

I added page beforeunload and unload functions as follows:
window.onunload = function (e)
{
//mycode1
return '';
};
window.onbeforeunload = function(e){
//mycode2
return '';
}
and they are getting called after browser confirmation popup occurs. But now I want to unbind these functions. I tried
window.onunload = null;
window.onbeforeunload = null;
But seems like they are not working and still browser refresh confirmation popup appears.

Can we detect browsers refresh and back button events?

Anybody know how to detect browsers refresh and back button events in firefox using jquery or javascript.
For back button:
window.addEventListener('popstate', function (event) {
//Your code here
});
For Refresh:
window.onbeforeunload = function () {
// Your code here
}
You can try WindowEventHandlers.onbeforeunload:
window.onbeforeunload = function(e) {
};
and
$(window).unload(function() {
//
});
Also check Browser Back Button Detection:
I have made a very reusable javascript class, that can be simply
dropped into your web page, and when the user clicks back, it will
call a function. The default function on this call is a javascript
alert “Back Button Clicked”.
To replace this functionality, you simply need to override the OnBack
function. This can be done by using the code below.
<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');
}
</script>
This will now replace the “Back Button Clicked” alert with a “You
clicked it!’” alert.
Check this page: Manipulating the browser history
You can probably get something working with using history.pushState and window.onpopstate
You can use the following events:
window.onpopstate for back button press.
window.onpopstate = (e) => {
// your logic goes here
};
window.onbeforeunload for refresh or tab close.
window.onbeforeunload = (e) => {
// your logic here
e.preventDefault();
e.returnValue = 'There are unsaved changes. Sure you want to leave?';
};

How to prevent navigation by browser buttons but not by links?

I want warn users if they leave the page by closing the browser or using the history buttons of the browser using the following javascript:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
But my links and buttons on my website should work regardless of this. How can I achieve that?
The first way that comes to mind is to set a variable that tells you whether a link was clicked:
var linked = false;
window.onbeforeunload = function(e) {
if (!linked)
return 'Ask user a page leaving question here';
};
document.addEventListener('click', function(e) {
if (e.target.tagName === "A")
linked = true;
}, false);
That is, set a click event handler at the document level, that tests whether the clicked element was an anchor (or whatever else you want to allow) and if so sets the variable. (Obviously this assumes that you don't have other anchor element click handlers at a lower level that stop event propagation.)
var linkClicked = false;
window.onbeforeunload = function(e) {
if (!linkClicked){
linkClicked = false;
return 'Ask user a page leaving question here';
}
};
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
});
});
Obviously this relies on JQuery to add the event handler to all links, but you could attach the handler with any other method, including adding onclick="linkClicked=true;" to every link on the page if you really have to.
Edit:
Just want to point out that if the user clicks a link that doesn't redirect them (e.g. a hashtag link to somewhere else on the page, or something that returns false / prevents the default action being executed) then this will set linkClicked to true and subsequently any browser based navigation won't be caught.
If you want to catch this, I would advise setting a timeout on the link click like so:
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
setTimeout(function(){
linkClicked = false;
}, 500);
});
});
This will allow half a second for the window unload event to trigger before resetting the flag so that future navigation events are caught correctly. This still isn't perfect, but it probably doesn't need to be.
You can use the window.onbeforeunload event.
var check= false;
window.onbeforeunload = function () {
if (!check) {
return "Are you sure you want to leave this page?"
}
}
function CheckBackButton() {
check= true;
}
referenceElement.addEventListener('onClick', CheckBackButton(), false);
Us a confirmation prompt no?
like this? Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
How to show the “Are you sure you want to navigate away from this page?” when changes committed? this may solve your problem How

Window closing even on clicking 'cancel' button in confirmation box

In my website i conduct an exam in new window & i want that if a user closes this window, he will be redirected to other page if he presses 'ok' on confirmation. But he should stay there if presses 'cancel'. The javascript i'm using is below.
/**
* This javascript file checks for the brower/browser tab action.
* It is based on the file menstioned by Daniel Melo.
* Refer: http://stackoverflow.com/questions/1921941/close-kill-the-session-when-the-browser-or-tab-is-closed
*/
var validNavigation = false;
function endSession() {
$choice = confirm("You will exit your CSA test. Are you sure you want to close the window?");
if ($choice)
window.open('Result.aspx', '_blank', 'toolbar=0, scrollbars=1');
}
function wireUpEvents() {
window.onbeforeunload = function () {
if (!validNavigation) {
endSession();
}
}
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function (e) {
if (e.keyCode == 116) {
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function () {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function () {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function () {
validNavigation = true;
});
}
$(document).ready(function () {
wireUpEvents();
});
Here on clicking 'ok' button the 'Result.aspx' window opens successfully, but the problem here is that if user clicks 'cancel' in the confirmation box then also the window is getting closed.
Please tell me where am i going wrong or any alternative to this.
Any kind of any help will be appreciated.
Thanks in advance!!
You can't actually stop the user from leaving your page. The final dialog (controlled by the browser), that asks if they want to stay on this page or leave, is up to them.
Your use of confirm() simply provides a dialog for the user, which you can get the choice from, but has no effect on the page being left. If you return a value from window.onbeforeunload, it prompts the user with that final dialog I mentioned, but you cannot capture their choice, nor can you control it.
There's nothing you can do to actually stop a user from leaving your page.

I want to call function on window unload

I am trying to display confirmation box using window.confirm on window unload event.
If a user clicks on the OK button on confirmation box then I want to call one function and if user clicks the CANCEL button then window should be get closed.
My code is:
<script>
function confirmit(){
var result=window.confirm("Are you sure?");
if(result) {
// close all child windows
} else{
// window should not get close
}
}
</script>
<body onunload='confirmit();' >
But the problem is if I click on CANCEL button, window is getting closed.
Please help me.
You can't prevent unload to stop the page from unloading. You need to bind to onbeforeunload instead. You should just return the string you want to display to the user from the event handler (note that in some browsers the string may not be displayed)
<script type="text/javascript">
window.onbeforeunload = function(e){
var msg = 'Are you sure?';
e = e || window.event;
if(e)
e.returnValue = msg;
return msg;
}
</script>
More info here
JSFiddle Example here
change your code to this to make it work cross-browser:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Do you really want to exit?';
}
// For Safari
return 'Do you really want to exit?';
};
</script>
<body>
...
note that this is using the onbeforeunload-event (more information / view an example) where the return-value has to be the message that should be shown to the user.
i don't know if you'll have a chance to react on the confirmation to do something after that (closing child-windows for example), but i don't think so.

Categories