Author: Xu Haiqiang

directory

  • Use gtag.js to support the web side of the browser
  • Support for the electron client
  • Combination of the desktop client and the Web client
  • The use of the userId
  • GTM collects click events

Xiao Blackboard PC client is a web and desktop client integrated project, the client uses the electron technology stack, the two are the same code. To collect some data, we adopted a buried solution using Google Analytics (GA). The following is the study of some application schemes of GA in our project.

Firstly, we checked the official website and provided three solutions. The survey found that the combination of the third application and the website could not meet our needs, so we chose the first two solutions and first compared the two solutions:

  1. In short, gtag.js is an upgrade to analytics.
  2. According to the official website, analytics. Js uses a tracker to send data to the GA, specifying the type of data using a match type. Gtag.js does not use a tracker to send data to the GAconfigThis directive sets the trackingID to identify GA resources.

Here’s a code example to make this clearer: send page browsing data, for example

// analytics.js
ga('create'.'UA-12345678-1'.'auto');
ga('send'.'pageview');
// gtag.js
gtag('config'.'UA-12345678-1');
Copy the code

Therefore, we adopted gtag.js scheme to carry out buried point collection. We injected JS according to the official website

<! -- Global site tag (gtag.js) - Google Analytics --><script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments); } gtag('js'.new Date());

  gtag('config'.'GA_MEASUREMENT_ID');
</script>
Copy the code

We can also create script tags with dynamic JS and then insert dom.

Use gtag.js to support the web side of the browser

We call this method in hashchange because we are a single-page application using hash routing

window.gtag('config', GA_MEASUREMENT_ID, {
    page_path: path,
});
Copy the code

Support for the electron client

  1. Ga defaults to a browser restriction
  • The host that sends the request to the GA requires HTTP or HTTPS
  • The host must support storing client ids in browser cookies
  • The host must be able to pass urls to the GA

Explanation: the electron client adopts the file:/// protocol, cookies are not available, the passed url path is not correct, and we found that gtag.js does not provide an API to disable cookies, while analytics. By default, the gTAG scheme not only mounts Gtag objects on the window, but also mounts GA objects. So we decided that our solution was

  • Ga scheme is adopted at the desktop end to bury the spot
  • Gtag scheme is adopted in the web end of the browser to bury the spot

Here are some specific operations:

  // Transfer the clientId stored in the cookie to localStorage
  const gaKey = window.localStorage.getItem(GA_LOCAL_STORAGE_KEY);
  if(! gaKey) {window.localStorage.setItem(GA_LOCAL_STORAGE_KEY, window.ga? .getAll()? .0].get('clientId'));
  }
  window.ga('create', GA_MEASUREMENT_ID, {
      storage: 'none'.clientId: gaKey
    });
  // Set path and send the correct path
   window.ga('set'.'checkProtocolTask'.null);
   // newpath is the path, we have hash value here
   window.ga('set'.'page', newPath);
  const re = /(.*)\/entry/;
  // ps: location This step is to be replaced according to the need, does not affect the buried point
  const location = document.location.href.replace(re, 'https://xxx.xiaoheiban.cn/entry');
  window.ga('send'.'pageview', {
    location
  });
Copy the code

Combination of the desktop client and the Web client

Previously, we adopted a set of GAID on the Web side and a set of GAID on the client side, but this is actually not very friendly to statistics. For this reason, we combined the two together after investigation and adopted the same GAID. The solution uses the custom dimensions of Google Analytics. In the media resources column of GA management pageHow to use new? Please refer to the official document for detailsSet a custom dimension, will not be repeated here.The GA dimension is hit by index

/ / the client
 window.ga('set'.'dimension1'.'eb'); // The 1 in Dimension1 represents the index of the figure above, and eb is the value you passed in
/ / web side
window.gtag('set', {
    custom_map: {
      dimension1: 'type_os' // The type_OS here is independent of the image, just to correspond to the type_OS in config below.}});window.gtag('config', ID, {
    page_path: newPath,
    type_os: 'web'
  });
Copy the code

Now that we have defined the above methods, how do we use them? Here toaudienceFrom the menuAn overview ofFor example, by clicking on overview, there is only one subdivision dimension for all users by default, so we click Add Subdivision.As above, save and add againtype_os === 'eb'The client of.Check the two checkboxes above and the page will already look like you want it toYou can see why the number of web users plus the number of clients is greater than 100%, but actually when we tested, some users were using both web and client.

The use of the userId

  1. Why use it

Ga provides us with userId identification. Ga uses clientId by default to perform calculation and report, but this also means that the system will record multiple sessions when users change browsers and computers. Therefore, in order to achieve the function of identifying unique users across multiple devices or multiple sessions, more accurate user data can be obtained, so as to better reflect the real situation.

  1. How to operate

The management page of ga is displayed. The UserId report is displayed in the new view

  1. Code operation
/ / the client
window.ga('set'.'userId', userId);
/ / web side
window.gtag('set', {
  user_id: userId
});
Copy the code

GTM collects click events

  1. What is a GTM research

Google Tag Manager, or GTM for short, is a tool that helps us add code to websites and apps easily and quickly

  1. Why use GTM
  • Using this tool, it is very easy to add code without having to find technology to do it every time, which greatly simplifies our work and improves our efficiency.
  • Using GTM can also speed up our website to a certain extent. Because GTM loads in one step, it can load faster.
  • Convenient for us to manage a variety of code and multiple sites, in addition to simple deployment code, it also looks very clear, easy to modify.
  1. case

Here we use the DOM binding data-ga to collect click events for example:

Test
{{element}} is the DOM element you clicked on
function() {
	var elem = {{element}}, i = 0, result = null;
    while (elem && i < 3) {
    if(! (elem.dataset && elem.dataset.ga)) { elem = elem.parentNode; ++i; }else {
      result = elem.dataset && elem.dataset.ga
      break; }}return result;
}
Copy the code

As you can see, the code above uses a maximum loop lookup of three times in order to deal with some antD components. Take Button as an example, you can see that if I click on the test word, it is just a span and does not bind data-GA.

<Button data-ga='1001'> test < / Button >// Render the DOM node on the page as
<button data-ga="1001" 
        type="button" 
  			class="ant-btn" 
  			ant-click-animating-without-extra-node="false">
  <span>test</span>
</button>
Copy the code

Once you have done this and embedded the original code into your page, use GTM debug. Click preview to enter the page, enter the address to debug, and click Start.As shown in the figure above, I clicked 5 times on the page, and clicked the Button with data-GA for 3 times, resulting in 3 hits, indicating that your GTM operation is ok.When we return to the GA page, we find that the click event has been passed to the GASo that’s the end of the demo. But the function of GTM is far more than this, very powerful function, you can explore interested.

  1. simulation

The above GTM binding DOM event reception, using GA API can also be replaced, I simulate here.

const isEB = window.navigator.userAgent.match(/electron/i);
window.addEventListener('click'.(event) = > {
let node = event.target as HTMLElement;
  let i = 0;
  // I want to go to the third floor
  while (node && i < 3) {
    if(! (node.dataset && node.dataset.ga)) { node = node.parentNodeas HTMLElement;
      ++i;
    } else {
      break; }}constid = node? .dataset? .ga;if(isEB) {
    window.ga('send'.'event'.'Test GA click'.'the test ga');
  } else {
    window.gtag('event'.'the test ga', {
      event_category: 'Test GA click'}); }})Copy the code

The resources

  • The official documentation
  • Google Analytics on site that uses file://
  • How do I track user behavior by adding GA-data to page elements