How to determine if the browser session just started or if it's a subsequent click?

送分小仙女□ 提交于 2019-12-12 02:52:41

问题


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?


回答1:


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




回答2:


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




回答3:


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.




回答4:


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());
  }
}


来源:https://stackoverflow.com/questions/24316934/how-to-determine-if-the-browser-session-just-started-or-if-its-a-subsequent-cli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!