0

I would like to figure out whether the browser session is brand new (user just fired up a browser and loaded my page) or a subsequent click-through.

How can this be done with JavaScript?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
TheOne
  • 10,819
  • 20
  • 81
  • 119

4 Answers4

2

Instead of window.referrer try document.referrer. I got it to work for me in chrome

Bryan
  • 21
  • 2
1

You can use window.referrer, although that's not a foolproof method, because some browser settings hide it for privacy purposes. It should work fine with most default settings, though.

It will give you undefined if the browser has just started up or the user has come there from a new tab, but keep in mind that if the user has a home page and comes to the site from there, it will give the home page. Also, if the user CMD/CTRL + clicks and opens in a new tab, it will throw undefined despite the fact that they clicked a link to get there.

With that said,

if(window.referrer){
  //stuff to do if clickthrough
}else{
  //stuff to do if new session
}

Demo

AstroCB
  • 12,337
  • 20
  • 57
  • 73
0

You could set a session cookie when the site loads on the initial page. Therefore when the site loads and you check if that cookie exists or not, you'll know whether it is a new session starting or not.

Michael Johns
  • 419
  • 3
  • 21
0

You can check for sessionStorage.length in your $(document).ready() function. If the sessionStorage length is equal to 0, then you can probably set an item like the time where you can store the time at which the page got loaded using jQuery.now(). Next time, if the page reloads, you can check for the length which will not be 0, showing that the same session still exists.

$(document).ready(function(){
  if(sessionStorage.length!=0){
    //do something
  }
  else{
    sessionStorage.setItem("time",jQuery.now());
  }
}