onUserExit - Execute Code When a User Leaves or Closes Your Website
Welcome to the demonstration page for the jQuery plugin onUserExit written by Scott Brooks at UserFirst Interactive. This jQuery plugin allows you to easily wire a function to execute when the user leaves your website.
How does it work?
I'm sure many of you have read about the javascript function onbeforeunload() or in jQuery $(window).unload() which triggers when a user leaves a page. Well the trouble is if the user clicks on the navigation within your website to go to a separate page from where you are currently (i.e. the user lands on the Home and then navigates to About), this triggers the event, which in this case you don't want.
The way this is achieved is that upon the page completing load, I actually add click methods to all internal links within the page that execute a function called "userMovingWithinSite()", which sets a boolean variable called "movingWithinSite" to true. So now, when the user clicks a navigation link or any link on the website WITHIN the website and the onbeforeunload event triggers, I can check to see if the user is actually leaving the site, or just navigating within it. If they are indeed leaving, then we execute your function!
Usage
Variables:
execute - code to execute.
internalURLs - used to detect whether the url is internal or not (you can add subdomains to this list so when a user hops between sites, they are still considered to be internal. Separate URLs with a pipe '|'.
Sample Code
Sample usage for onUserExit:
$(document).ready(function() {
$().onUserExit({
execute: function()
{
alert("This alert was executed upon you leaving this page to another website, or when you closed the browser!");
},
internalURLs: "creations.userfirstinteractive.com|www.userfirstinteractive.com"
});
});
Here are some links to test out how it works.
Internal (won't trigger): UserFirst, UserFirst Blog
External (will trigger): jQuery, Google
I'm sure you all will find some great uses for this plugin! Enjoy!
Update
Verision 1.1 Released - fixed issue where form submission would trigger the onUserExit event. Added detection of Ctrl+R & F5 button pressing... these no longer will fire OnUserExit event either.
Download
Plugin
Requires the jQuery URL Parser (included)
Download version:
Version 1.1 - onUserExit js file
Download the complete demo here.
Questions? Comments?
We'd love to hear from you! Visit our blog and let us know what you think of our creations!
