Search code examples
javascripthtmlgoogle-analyticsonbeforeunload

What are all the possible causes of firing onbeforeunload event?


I am writing some code to track user behavior on my website in order to improve conversion rate by determining how users are interacting with my website.

This requires me to send some events like "Leaving Website" to Google analytics inside the unbeforeunload handler. I have a few questions about the firing of this event.

  1. Does it fire if user switches tabs without opening a new link?
  2. Does it fire if a new tab is opened after users clicks a link with target="_blank" on my website?
  3. Does it fire if a users visits some other page of my own website?
  4. Does it fire on page reload?

Are there any other instances where it fires?

Thanks.


Solution

  • onbeforeunload will fire right before a webpage is 'unloaded' in the current tab (By navigating to a new page), or the current tab is closed. This means:

    • When a user navigates to a new page on or off your website.
    • When a user closes the tab or browser
    • When a user refreshes a page
    • When a user submits a form

    To answer your questions

    1. Does it fire if user switches tabs without opening a new link?

    No

    1. Does it fire if a new tab is opened after users clicks a link with target="_blank" on my website?

    No

    1. Does it fire if a users visits some other page of my own website?

    Yes

    1. Does it fire on page reload?

    Yes

    The current version of analytics.js should (Using sendBeacon()) dispatch events to GA as a POST request, which should be honoured even when closing tabs or the browser.

    However, I wouldn't be so sure that 'Leaving website' is appropriate. Perhaps something more like 'Leaving page'.