[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 套件
- npm i react-ga4
2.初始化 GA
- import ReactGA from 'react-ga4'
- ReactGA.initialize('G-XXXXXXXXXX') //你的GA評估ID
3.將 url 加入 GA
- ReactGA.send('https://www.xxx.xxx') //你要偵測的URL
理論上加完,並執行該網頁,就會在GA平台上看到如下的狀況
4.將 button 加入 GA
- const gaEventTrack = () => {
- // body 外無 hasAttribute 方法,避免錯誤
- const body = document.querySelector('body');
- body.addEventListener('click', (e) => {
- let target = e.target;
- // 查找元素不包含 data-ga-action,且到 BODY 後跳出
- while(target.hasAttribute('data-ga-action') === false && target.tagName !== 'BODY'){
- // 父元素覆寫當下元素
- target = target.parentNode;
- }
- if(target.hasAttribute('data-ga-action')){
- const dataGaCategory = target.getAttribute('data-ga-category'); // 分類:網站頁面
- const dataGaAction = target.getAttribute('data-ga-action'); // 事件:功能名稱
- ReactGA.event({
- category: dataGaCategory,
- action: dataGaAction,
- });
- return false;
- }
- }, false);
- };
- useEffect(() => {
- gaEventTrack();
- }, []);
5.將 select 加入 GA
- const gaEventTrack = () => {
- ...
- 4. button
- ...
- // select 專用
- body.addEventListener('change', (e) => {
- let target = e.target;
- // checkbox 跳出
- if(target.tagName === 'INPUT') return;
- // 查找元素不包含 data-ga-action,且到 BODY 後跳出
- while(target.hasAttribute('data-ga-category') === false && target.tagName !== 'BODY'){
- // 父元素覆寫當下元素
- target = target.parentNode;
- }
- if(target.hasAttribute('data-ga-category')){
- const dataGaCategory = target.getAttribute('data-ga-category'); // 分類:網站頁面
- const dataGaAction = target.value; // 事件:功能名稱(取得 option name)
- ReactGA.event({
- category: dataGaCategory,
- action: dataGaAction,
- });
- }
- }, false);
- ...
- 4. useEffect()
- ...
- };
6.將其寫成 component 置於 src/index.js
- const GATracker = () => {
- const gaEventTrack = () => {
- ... 4. button
- ... 5. select
- ... 4. userEffect()
- };
- }
- const Main = () => (
- ...
- <GATracker/>
- ...
- );
留言
張貼留言