How would you count a user's accumulated visits to your site client-side?

冷暖自知 提交于 2021-02-07 10:50:18

问题


I want to keep track how many times a user has visited my site/domain. For example, say I wanted to display a message to the user after their 10th visit to the site. Each pageload should not count as a new visit. A visit in this case is more like a session. Browse all you want in one sitting, that's one visit. Close your browser and come back, that's a second visit.

I thought it would be good to do this by utilizing localStorage and sessionStorage. I put a value in sessionStorage to show that a user is on a "currentVisit" so that I don't count them on every pageload. This gets wiped out when their session ends. Then I have a value in localStorage that tallies up the total amount of visits by the user, "visitCount". If a user loads a page and doesn't have a "currentVisit" value, give them one and increment "visitCount".

I'm worried about using local/session storage though because I've read it is not consistently supported across all browsers, specifically mobile ones.

I'm considering using indexedDB in place of localStorage and session cookies in place of sessionStorage in my approach. What do you think is the right tool for the job?


回答1:


While using a polyfill as I mentioned above, you can define a simple function like this to keep track of a user's visits assuming they're not in incognito or private browsing mode, and they don't clear or disable cookies for your site:

function visitCount() {
  var visits = Number(localStorage.getItem('visitCount'));
  var current = Boolean(sessionStorage.getItem('session'));

  if (!current) {
    visits++;
  }

  localStorage.setItem('visitCount', visits);
  sessionStorage.setItem('session', true);

  return visits;
}

If you're concerned with any of the caveats of trusting client-side storage (for example, security) then you should use a server-side solution and a browser fingerprinting script to keep track of anonymous visits in a more robust manner.



来源:https://stackoverflow.com/questions/49013384/how-would-you-count-a-users-accumulated-visits-to-your-site-client-side

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