detect user leave page

How to Detect When User Leaves Page

It is important to retain website visitors as long as you can, to increase conversion rate and grow your business. So often web developers need to be able to detect when a user leaves their website or application, so they can try some ways to retain them and prevent them from leaving. In this article, we will learn how to detect when user leaves page using JavaScript.

How to Detect When User Leaves Page

You can implement this using plain JavaScript or using third-party JS libraries like jQuery. We will look at both these approaches.

Most modern web browsers support onbeforeunload event that is fired when user leaves a web page. It even allows you to ask user if they really want to leave. We will use this for our purpose.

1. Using Plain JavaScript

You can easily detect when user leaves your web page by simply adding the following JavaScript to your page.

<script language="JavaScript">
  window.onbeforeunload = confirm_exit;
  function confirm_exit()
  {
    return "Are you sure you want to exit this page? All your unsaved changes will be lost.";
  }
</script>

In the above code, we define an event listener function confirm_exit() that will be fired when event onbeforeunload is fired, when the user tries to leave the page. We have set up a warning message to be displayed to the user when confirm_exit() is called. You can customize this function as per your requirement.

Alternatively, you can also call this function when mouseleave event is fired. It is accurate in most cases, but not always.

<script language="JavaScript">
  window.mouseleave = confirm_exit;
  function confirm_exit()
  {
    return "Are you sure you want to exit this page? All your unsaved changes will be lost.";
  }
</script>

2. Using jQuery

You can also do the same thing using third-party libraries like jQuery.

<script language="JavaScript">

$(document).bind("onbeforeunload", function(e) {
    confirm_exit();
});

function confirm_exit()
  {
    return "Are you sure you want to exit this page? All your unsaved changes will be lost.";
  }

</script>

Here too you can bind the event listener to mouseleave event.

$(document).bind("mouseleave", function(e) {
    confirm_exit();
});

In this article, we have learnt a couple of simple ways to detect when user leaves a web page. You can use it to detect and prevent users from leaving your website or web application. You can also use it to pause videos playing on your website, when user leaves the web page, and make your website for intuitive.

Also read:

How to Generate PDF from HTML using JavaScript
How to Auto Resize IFrame Based on Content
How to Count Substring Occurrence in JS String
How to Convert Comma Separated String into JS Array
How to Suppress Warning Messages in MySQL

Leave a Reply

Your email address will not be published. Required fields are marked *