且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每个会话只发送一次事件?

更新时间:2022-12-26 20:15:59

Google Analytics events are a hit type (like pageviews) which can not be scoped to sessions or users. Even if you could only send one event per session (using either cookies or sessionStorage, you wouldn't actually get the whole picture in your GA reports.

To offer a better solution, consider using a Custom Dimension with a scope of "session" to store that data. What's cool about this is that the dimension is applied to all hit types within the scope- meaning any pageview, event, etc. also has the dimension associated with it.

To do this, create the dimension in Google Analytics Admin under the Property settings within Custom Definitions. Get the index number (a string that looks like 'dimension1' or 'dimension 4') and paste the line BEFORE sending the pageview (ideally) or an event.

Remember: Dimensions are not hits, so simply setting them does nothing until a hit is also sent! Also, be sure to enable non-interaction on the events (if that is the route you choose) or else you will be misreporting bounces from those using Ad Blockers.

Here is the ideal snippet (Note: if you are going to setTimeout as part of your detection, do not use this method as it would delay the pageview send too... Consider a method that doesn't need a timeout.):

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-Y', 'auto');

//Detection goes here. If true:
ga('set', 'dimension1', 'Ad Blocker'); //Change 'dimension1' to yours.

ga('send', 'pageview');
</script>

Your code from above would look like this if you can't do the detection before the <head> GA send pageview snippet.

function test(){
     var len = $('.ad').length;
     if(len === 0){
         ga('set', 'dimension1', 'Ad Blocker'); //Change 'dimension1' to yours.
         ga('send', 'event', 'Ad Blocker', {nonInteraction: true}); //Add action and label as needed.
     }
 }