[React] react 使用 Google Analytics - 追蹤 button、select

react 使用 Google Analytics (以下簡稱GA),
你也可以不使用套件,直接使用GA上提供的「全域網站代碼(gtag.js)」




1.安裝 GA 套件
2.初始化 GA
3.將 url 加入 GA
4.將 button 加入 GA
5.將 select 加入 GA
6.將其寫成 component 置於 src/index.js


1.安裝 GA 套件
  1. npm i react-ga4


2.初始化 GA
  1. import ReactGA from 'react-ga4'
  2. ReactGA.initialize('G-XXXXXXXXXX') //你的GA評估ID


3.將 url 加入 GA
  1. ReactGA.send('https://www.xxx.xxx') //你要偵測的URL

理論上加完,並執行該網頁,就會在GA平台上看到如下的狀況




4.將 button 加入 GA
  1. const gaEventTrack = () => {
  2. // body 外無 hasAttribute 方法,避免錯誤
  3. const body = document.querySelector('body');
  4.  
  5. body.addEventListener('click', (e) => {
  6. let target = e.target;
  7.  
  8. // 查找元素不包含 data-ga-action,且到 BODY 後跳出
  9. while(target.hasAttribute('data-ga-action') === false && target.tagName !== 'BODY'){
  10. // 父元素覆寫當下元素
  11. target = target.parentNode;
  12. }
  13.  
  14. if(target.hasAttribute('data-ga-action')){
  15. const dataGaCategory = target.getAttribute('data-ga-category'); // 分類:網站頁面
  16. const dataGaAction = target.getAttribute('data-ga-action'); // 事件:功能名稱
  17. ReactGA.event({
  18. category: dataGaCategory,
  19. action: dataGaAction,
  20. });
  21.  
  22. return false;
  23. }
  24. }, false);
  25. };
  26.  
  27. useEffect(() => {
  28. gaEventTrack();
  29. }, []);


5.將 select 加入 GA
  1. const gaEventTrack = () => {
  2. ...
  3. 4. button
  4. ...
  5. // select 專用
  6. body.addEventListener('change', (e) => {
  7. let target = e.target;
  8.  
  9. // checkbox 跳出
  10. if(target.tagName === 'INPUT') return;
  11. // 查找元素不包含 data-ga-action,且到 BODY 後跳出
  12. while(target.hasAttribute('data-ga-category') === false && target.tagName !== 'BODY'){
  13. // 父元素覆寫當下元素
  14. target = target.parentNode;
  15. }
  16.  
  17. if(target.hasAttribute('data-ga-category')){
  18. const dataGaCategory = target.getAttribute('data-ga-category'); // 分類:網站頁面
  19. const dataGaAction = target.value; // 事件:功能名稱(取得 option name)
  20. ReactGA.event({
  21. category: dataGaCategory,
  22. action: dataGaAction,
  23. });
  24. }
  25. }, false);
  26. ...
  27. 4. useEffect()
  28. ...
  29. };


6.將其寫成 component 置於 src/index.js
  1. const GATracker = () => {
  2. const gaEventTrack = () => {
  3. ... 4. button
  4. ... 5. select
  5. ... 4. userEffect()
  6. };
  7. }
  8.  
  9. const Main = () => (
  10. ...
  11. <GATracker/>
  12. ...
  13. );





留言

這個網誌中的熱門文章

[面試] 日月光 設備工程師

[日文] Google日文輸入法 簡單安裝說明

[Windows] 還我 win7 相片檢視器!!