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?
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?
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 + click
s 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
}
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.
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());
}
}