Is there a way to call a JavaScript when the window closes or the address goes to a completely different site, not just when the page changes? I know I can use onunload, but that seems to trigger when the page changes.
I have an intranet site that I need to keep track of logging in and out. Instead of users always clicking on "Log Out", some of them just close the browser window.
I have an idea. Fire off an AJAX call to some page that "keeps-alive" the current user's session every 30 seconds or so. After a certain time of inactivity (maybe 40 seconds? Make sure it's greater than 30), the server knows the client has become inactive and can log you out. This might seem like overkill, but it's the only way to reliably know when the user is no longer active. Firing off a call when the window is closed might seem like it'd be good, but if the browser crashes or the computer is turned off or something, the call never gets sent anyway.
window.onbeforeunload = function(){
$.ajax({ url : logoutuser?id=xyz,
async : false
});
};
This will work if when trying to close the window..
One other way is to route all your clicks (for links) on your page through your own custom method -
window.location.href = "someurl";
So that way you can sniff where the user tried to navigate to..
For now, unless someone can come up with a better idea, I have the site running in a 100% frame and the onunload script setting on the default page with the frame layout.
Related
So I am working on a testing application and I need to call a finsihTheTest() function (i.e. this function finishes the test by saving answers, time and other information) whenever following conditions occur:
User tries to reload page.
User tries to go back from the page.
User tries to close the tab.
User tries to close the browser window.
User goes to another url.
If anything happens that closes the page like laptop/PC shutdown, internet lost or anything else.
What I exactly want to do is, if once a user starts the test and by any mean he attempts to leave I want to save his state. Which is being done by the function finishTheTest().
I got a clue but it didn't work:
function UnLoadWindow() {
return 'We strongly recommends NOT closing this window yet.'
}
window.onbeforeunload = UnLoadWindow;
To get the full results for your cases there's many things you should now on how browsers react on many scenarios.
To understand more please read this section :
Especially on mobile, the unload event is not reliably fired. For example, the unload event is not fired at all in the following scenario:
A mobile user visits your page.
The user then switches to a different app.
Later, the user closes the browser from the app manager.
Also, the unload event is not compatible with the back/forward cache (bfcache), because many pages using this event assume that the page will not continue to exist after the event is fired. To combat this, some browsers (such as Firefox) will not place pages in the bfcache if they have unload listeners, and this is bad for performance. Others, such as Chrome, will not fire the unload when a user navigates away.
If you're specifically trying to detect page unload events, it's best to listen for the pagehide event.
window.addEventListener('pagehide', function(event) {
document.cookie = "saveData=test"
},false)
This way you can save your user current data and reload it on next page window load event
I am developing a web application. And I wrote some JS script to be executed on document ready. But in chrome when we click on back button and go back to previous page it is executing all the js script again. But when I use same on firefox it do not execute the JS.
I have an accordion on a page and when user open any accordion and go on one of the link under the accordion and after that if again clicks the back button on the accordion page chrome is closing all the accordions as I have written the script to close all these on document ready. But firefox do not close.
Is there any way to fix this with javascript? So that I can put any condition like if(history.forward.length < 1){ do this....}
You can use the pageshow event to guarantee you always detect navigation to a particular page, regardless of whether the user presses the back/forward button or selects a link, and regardless of which browser is being used.
Then you can perform checks regarding the state of UI and perform logic as required (i.e. modify UI, prevent execution of additional JS).
window.addEventListener('pageshow', function(event) {
// check state of UI, etc.
});
The solution that came to my mind is using sessionStorage to know if it is a first time loading or not. Or even better, you can keep state of your accordions in session storage so it always be the way the user want.
In my case, the iframe was a hidden iframe (width and height zero).
This iframe is just an workaround from legacy system, developed 12 years ago. But still using nowadays on current application.
To solve it, i just redirected the page loaded into iframe to the blank page.
Example:
page_loaded_into_iframe.php
<?php
//do the php stuffs
?>
<script>
alert("hello world");
location.href = "about:blank"; // here, where the the magic happens!
</script>
Once pressed the "back button", the browser will reload a blank page.
Be aware that this might be not applicable if your case is not similar to mine.
In the Chrome Extension you can use the function:
chrome.webNavigation.onCommitted.addListener(function callback)
and in the callback function you may take a look to the arguments:
transitionType + transitionQualifiers
to look for:
"forward_back" The user used the Forward or Back button to initiate the navigation.
For deatils see chrome.webNavigation
Of course, this event can be communicated to the content script with the usual message model (refer to: Message Passing
I want to clear session when browser window closed. But when i am trying to use window.unload event, it triggers also when back button clicked. How can i avoid it?. And clear session on window close.
The other posters are correct. There is a reason you see the following setup on 99% of sites.
Offer the users a logout button to close the session.
Otherwise time out the session after they have been inactive for 1+ hours depending on your paranoia level.
Unfortunately clearing the session on unload() is not a good way to do it. In fact that unload handler will even fire when they go to other pages on YOUR SITE. I highly doubt this is the approach you want to go with.
There is no way to do this that I know of. It would be a security issue if you were able to tell when someone is leaving your page for another or closing the browser.
As far as your page's security model is concerned once someone is off your page there's no telling what's happening anymore
The only way to know if someone has left your site is if... they stop loading pages.
You're best bet is to track a "Last Impression" time in the session in your server application. Update it to now every time they make a page request. If their Last Impression is ever more than, say, four hours old, you know they left for a while, so invalidate their session and start a new one for them.
Is it possible to redirect to another page when the user closes the browser?
Attempts:
I tried onunload, does not work
window.onunload = function redirect(){...}
I also tried another method, it doesn't work either:
window.onbeforeunload = redirect(){...}
<body onbeforeunload="return false; redirecty()">
The 3rd method, I want to cancel the onbeforeunload (means delay closing the browser), the I call the redirect function, window.confirm, if yes redirect, if no then close the browser. But it does not work as well.
Is there any other way?? Maybe prompt to let user select whether to redirect to new page when he/she close the browser? I'm running out of ideas...
Your onbeforeunload event needs to return a string (that doesn't equate to false), the browser will include this string in its own message displayed to the user.
window.onbeforeunload = function(){
location.assign('http://www.google.com');
return "go to google instead?";
}
However, it's going to be really tricky to word your message in a way that the user would be able to understand what to do. And I'm not sure this is robust in every browser, I just tried it in Chrome, it worked, but I ended up with a tab I could not close! I managed to kill it via the Chrome task manager thankfully.
It's not without it's faults but it works
window.onbeforeunload = function(){
window.open("http://www.google.com","newwindow");
return "go to google instead?";
}
This will open a new window as a popup to the address you selected when the user closes the page, though it is limited by any popup blockers the browser may implement.
If the user is trying to close the browser, then his intentions are pretty clear; he expects that the browser will close. Preventing that from happening, or causing anything else to happen in between the user clicking on 'close' and the browser closing is just a bad idea IMO. Is there a special reason for this? I mean, when I click on the 'close' button I expect that the browser will close, and should anything else happen, I would find that extremely annoying. I think I'm being reasonable enough. Am I? Who knows such things.
Why don't you try to entice the user to visit the other page in a less intrusive way? Like with a link or a banner?
The simple answer is no. If browsers allowed you to do more with the onbeforeunload/onunload events, this could be used pretty maliciously by anybody.
I'm trying to get this JavaScript to work properly. My intention is, when a user is trying to close the site page to get an alert saying "stay on current page or close" If they hit 'ok' I want it to close, if they hit 'cancel' i want it to redirect to another page. The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing, not when leaving the page to another page. I'm not sure if that's possible, I do appreciate your help and comments.
window.onbeforeunload = fget;
function yPop(url) {
var found = 1;
window.onbeforeunload = '';
window.location = url;
return false;
}
function fget() {
alert("Thank you for visiting our website, you are welcome any time! \n\n");
window.location = "http://NewLink.com";
return "\n________________________\n\n PRESS 'CANCEL' To Stay On The Current Page \n\n________________________\n";
}
The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing
Don't do this.
You can't detect closing only, but you can tell the difference between leaving by clicking on an internal link and other kinds of leaving, including external links, back button, closing and choosing/typing a new URL. In a script after the page has loaded, set the onbeforeunload event, then scan over all the document.links and test their .host against the current location.host. If they match, it's an internal link. In this case add an onclick event to them that removes the onbeforeunload event before returning true, allowing the link to operate normally without a warning.
Seriously, don't do this. It is incredibly irritating, arrogant and useless. Webmasters who employ leaving-pester scripts are condemned to the the fourth circle of internet hell, where they must spend the rest of eternity making stylesheets work on Netscape 4 using only ed, a worn toothbrush and a < layer>-tag.
you should use the window onbeforeunload Event.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
https://developer.mozilla.org/en/DOM/window.onbeforeunload
for jquery users :
$(window).unload( function () { alert("Bye now!"); } );
You may want to consider building a "You're about to leave this site" page instead.
The idea is that you wrap URLs on the page that aren't on your site to point to that page, letting the visitor know they're about to leave, and giving them a chance to go back, or proceed.
It's gentler than an unexpected modal dialog, it lets you format your messaging better, and it ultimately gives your users the exact same choice.