JavaScript body onunload not working - javascript

Hi I have the following code:
function redirect(){
window.location.href='logged_out_chat.php';
}
...in my header and the following body tag:
<body onunload="javascript:redirect();">
...when i try this on one laptop, it redirects as it is supposed to (when you click on any link), but on my other laptop, desktop and notebook it ignores the redirect and goes to any link you click on.
I have spent hours on this...all have the same browser. I was wondering if there is an alternative way i could redirect the user when they click on a link etc.

What do you expect would happen?
When I close your page in my browser you get to redirect me to a page of your liking?
This goes againts security and user control. You shouldn't be able to interfere with the page when I close it.
The morale is don't rely on onunload to do anything non-trivial.

When a window unloads it stops processing everything, that means ajax requests, pending downloads etc, most even freeze animated gifs. Some browsers support onbeforeunload, but I completely agree with #Raynos you can't count on the event, so using it is not a good design decision.

You can't hijack onunload and redirect the user. That would prevent the user from closing their browser, refreshing the page, or manually navigating to another site. If that's what you are trying to do, you are out of luck. All onunload is good for is asking the user if they are sure they want to leave the page.
If, however, you are trying to cause a clicked link to go to a different location, that's easy. To change the link permanently:
myLink.href = 'logged_out_chat.php';
If you want to change the links temporarily, add a click handler that you can later remove:
function goToLoggedOutChat(e)
{
e.preventDefault && e.preventDefault();
e.returnValue = false;
location.href = 'logged_out_chat.php';
}
mylink.onclick = goToLoggedOutChat;
To re-enable the link:
mylink.onclick = null;
To do it for every link on the page:
for (var i=0; i<document.links.length; i++)
{
document.links[i].onclick = goToLoggedOutChat;
}

Related

window beforeunload is not working as expected in jquery

Basically what i am trying to do was, whenever a user tries to close the current tab(when he was on my site), i want to display a pop up with three choices about why he was leaving and want to store that choice some where
So i have written the following in main.js which will be loaded through entire site pages
$(document).ready(function() {
// Before closing the current tab, ask user for a reason
$(window).on('beforeunload', function(event){
$('#load_choices_up').click();
event.stopPropagation();
event.preventDefault();
debugger;
});
});
So i have three issues with the above jquery code
*.This code was executing even when i click another link on the same page(I mean if i navigate to another page from current page), but i only want this code to run when the current tab/page was closed(about to close) completely, but not when navigating to another page on my site
*. After this line $('#load_choices_up').click() was executed, a choices pop up was opening as expected, but immediately the default processing of browser(that is closing functionality) was not being stopped with two lines event.stopPropagation(); and event.preventDefault();, i mean these two methods of stopping the behaviour is not working and the browser is closed, but i want to do some processing based on user choices input and then based on that i will close tab.
*. When i used return "Why do you want to leave the page", instead of choices pop up, the browser was displaying different message based on browser type like "You have unsaved changes" in chrome, and some different message in firefox, instead of displaying my custom message
So finally, why event.stopPropagation(); and event.preventDefault(); are not working ? and why i can't able to display my custom message ?
You can't prevent someone from closing the browser. This is for obvious security reasons. Imagine a spam-website preventing you from closing the website while pumping you full of god knows what.
You can at most pull one function like an alert() or a prompt. After a user closes them, the tab will close either way.
beforeUnload is also extremely short-timed. You won't be able to run massive scripts with it, as the user would probably close the tap before any script would run properly. (I tried it with an ajax call, didn't work)
So, even if you're able to get the options you want in there, the moment a user chooses one of the options, you're not going to be able to save it anywhere. Your script will never make it that far.
You can customize the "are you sure?" message like so:
$(document).ready(function() {
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
});
but again, you can only change the text. It's a browser's native functionality, and you cannot change it.

Beforeunload is not working to redirect user to another page, how can I redirect user to another page/url when he attempts to close a window/tab?

My following code isn't working to redirect the user to another page:
$(window).on('beforeunload',function(){
window.location.href="http://www.google.com;
}) ;
I want the user to be redirected to another page when he attempts to close the tab.
What's the alternative and appropriate way to achieve this?
*Don't do it*
But it is possible with the user's permission; you can achieve something like this (took me a while to find a website that was happy in a frame)
window.onbeforeunload = function () {
window.setTimeout(function () { // escape function context
window.location = 'http://bbc.co.uk';
}, 0);
window.onbeforeunload = null; // necessary to prevent infinite loop
// that kills your browser
return 'Press "Stay On Page" to go to BBC website!';
// pressing leave will still leave, but the GET may be fired first anyway
}
Demo
I don't think this is possible.
There are some things you can can do in this event but that is severely limited due to spammers back in the day. They used to have animated text in the window statusbar which would obscure link href's so you would be clicking blind and open tons of windows when you tried to leave so that you were essentially trapped on the site.
This got to be such a problem that as far as I recall it was one of the "features" that Firefox bragged about solving when it first launched.
It was toned down to being able to beg them to stay with a dialog box but then that was abused as people worded it like official system messages and tricked people.
Now most browsers let you request a "stay on page / leave page" dialog but dont give you any control over the wording.
Here are some docs that list your options:
https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload

Differentiate browser refresh and browser close

I want to set a cookie when a visitor on the page closes the browser.
I used onbeforeunload method like this
<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>
followed this link
But found out that even refresh of page or click on any hyper link on the page,pops up an alert.
I need to set cookie only when visitor clicks cross button of browser and not on page refresh.
I followed some of the links like the one above and another here. And found from the post that we can not differentiate between close and refresh. But those posts were 3-4 years back.
Is there is any way to differentiate these events using JavaScript or Jquery?
I'm afraid you have no way to tell.
The only thing you can do is overload clicks on links and set a flag. But you can never know if it is a refresh or a close...
Hmm, what about this:
Set a cookie onbeforeunload
Globally onload, check the timestamp of the cookie to see whether this was a link, or a new session
If the timestamp difference is only a few seconds, delete the cookie
Well, unload is called when browser is closed and onload is called when you try to reload. You can use these properties and set flags , and fire events accordingly
Browser close and reload Check this link for more details

window.onunload fires and then the user clicks stop

Here is the flow I am trying to figure out.
User hits my page.
User clicks a link and onbeforeunload and unload get fired. Here i am getting rid of href in some of my links.
The page now hangs for a little bit giving the user a chance to hit the stop button in the browser.
Since the page is still on the original page (not the new page that was requested and then stopped) the hrefs are still blank.
Is there any way of knowing if the user clicks a stop button and they are still on the same page?
The only way I can think off the top of my head is to put a setTimeout in the onbeforeunload or unload but I don't really like that because there are too many variables for it still being messed up.
What I ended up doing was this:
window.unload = function(){
var _href = $('selector').attr('href');
$('selector').attr('href', '');
setTimeout(function(){
$('selector').attr('href', _href);
}, 1500);
}

Is there anyway to prevent onbeforeunload event from triggering when using Internet Explorer

I have a function that is suppose to trigger when user closes their browser and I have put the code in the window.onbeforeunload function.
The thing is every time if I reloads the page in Internet Explorer, the onbeforeunload event will also trigger which is a problem because I only wants it to trigger only when the user closes or navigates away from the current page but not on a page refresh/reload.
Therefore I'm not sure if onbeforeunload is intended to trigger even on a page refresh/reload and if it is intended to, then is there another way to work round it?
Since you are relying on javascript as it is, you may want to look into resolving the issue as to why they have to refresh the page. You can use XMLHttprequest to refresh the content for them so that the desired onbeforeunload function is only called when it needs to be.
There's no smart way to work around it. Any unloading action on the page will fire the unload and beforeunload events and there's no way to tell the difference between a refresh and a navigation.
You could attempt a couple of things, but there's no 100% method. For instance, capturing the F5 or Ctrl+R keys would identify a refresh, for which you could unset the onbeforeunload handler, but it would not work for users who click the refresh/reload button on their toolbar. You could attach an event handler to all clicks on an <a> element or any <form> onsubmits, but this wouldn't help for users who type a new address into the address bar from your page.
Even if you use XMLHttprequest to refresh, IE has a problem. You have to call the javascript function that contains the XMLHttprequest, for example,
click to add content
will trigger an onbeforeunload event on IE, but not on Safari or Firefox.
One solution that'll work in some situations is to handle the event conditionally, turning it off when you want to load content then turning it back on
var guard = true;
function myOnbeforeunloadHandler()
{
if(guard)
{
return "you are about to leave the page and lose data";
}
}
function addContent()
{
getElementById("myDiv").html = "<p>some content</p>";
guard = true;
}
<a href="javascript:void(0) onclick="guard=false;addContent();> click to add content</a>

Categories

Resources