JavaScript: window.onbeforeunload
Hi all, I am using window.onbeforeunload to keep people from accidentally leaving. I was hoping to intercept this event, run my own dialog box and load another page that closes the window, or of course, cancel.
I'm needing this because my site is a single page and I can't figure out how long people are visiting for, if I could load an exit page, then I can figure this out. Thanks! |
If you're asking for a way to create your own custom dialog box then you can't. Your best bet is to run a confirm JS dialog when the user is leaving the page. From there based on the result you can either return false (don't follow) or have it location.href (go to another webpage).
It is a netscape security feature that JavaScript can't close a window with window.close() unless that window was opened by JavaScript with window.open. I'd like to inform you that 99% of users will hate a feature that blocks them from leaving your site. I know I would (FYI). edit: another method would be to simply load an exit page with window.onbeforeunload and in the exit page have a window.onload function which would throw a dialog box for the user to confirm that they wish to leave. You could use the history to go back or a form submission to go forward. |
I was thinking that was going to be the answer. I had this without a function name previously, but here is what I have now. How would I do a confirm? And would the yes reply even be able to process anything further?
Code:
window.onbeforeunload = confirmExit; Thanks again! |
From what you want to do I don't think it can be easily done with clientside JavaScript. It is a security feature because you don't want browsers being hijacked with JS. I did find a little hack which prevents a user from leaving a webpage. But I doubt you'd have a use for it.
Code:
window.onbeforeunload=function(){window.setTimeout(function() { window.location.href=window.location.href; }, 10)} |
yeah things are not looking good, cool script though, that would be a real pia for the end user!
Basically the issue is that I have no idea how long people are staying on my page, it's all ajax and js, and without an exit page I can't figure this out. I guess this is the classic flash website problem. Thanks! |
I decided to research how flash sites handle GA, well I wasn't horribly surprised, but I found some nice features that would work for me. In all my 'page loads' (ajax calls) I call the same function to handle everything, so I came up with this snippet...
Code:
function gaPush(a,b,c) { Thanks All! |
Why don't you just have Ajax links load the content and any links that lead off-site simply call them with a target="_blank".
That's what I do on my website. I'm curious, why do you want to know how long people are at your site? If you're still intent on using JavaScript you could do something like the following: Code:
var arrive=new Date(); |
All times are GMT -5. The time now is 08:01 AM. |