0

在我的 Nextjs 项目(Nextjs v10)中,应所有者的要求使用了 2 位分析师。最初它只是谷歌分析,后来添加了 gtag。

我最近尝试的所有操作都不包括 gtag,但有时它们会通过增加跳出率来影响谷歌分析。

_app.js

import App from 'next/app';
import Router from 'next/router';
import { initGA, logPageView } from '../app/analytics';
import * as gtag from '../app/gtag';

class MyApp extends App {
    constructor(props) {...}

    static async getInitialProps({Component, ctx}) {...}

    componentDidMount () {
        initGA();
        logPageView();
        gtag.homepage();
        // save possible previously defined callback
        const previousCallback = Router.onRouteChangeComplete;
        Router.onRouteChangeComplete = (url) => {
            // call previously defined callback if is a function
            if (typeof previousCallback === 'function') previousCallback();
            logPageView();
            url && gtag.pageview(url);
        };
    }

    render() {...}
}

_document.js

import { GA_TRACKING_ID } from '../app/gtag';
import Document, { Html, Head, Main, NextScript } from 'next/document';

class MyDocument extends Document {
   render() {
      return (
         <Html>
             <Head>
                 ...
                 <script
                    async
                    src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}/>
                <script
                    dangerouslySetInnerHTML={{
                        __html: `
                        window.dataLayer = window.dataLayer || [];
                        function gtag(){dataLayer.push(arguments);}
                        gtag('js', new Date());
                        gtag('config', '${GA_TRACKING_ID}', {
                        page_path: window.location.pathname,
                        });
                    `,
                    }}
                />
             </Head>
         </Html>
      )
   }
}

分析.js

import ReactGA from 'react-ga';

export const GA_ID = 'UA-XXXXXXXX-1';

export const initGA = () => {
  ReactGA.initialize(GA_ID, {
    // debug: true,
  });
};

export const logPageView = () => {
  ReactGA.set({ page: window.location.pathname });
  ReactGA.pageview(window.location.pathname);
};

export const logEvent = (category = '', action = '') => {
  if (category && action) {
    ReactGA.event({ category, action });
  }
};

export const logException = (description = '', fatal = false) => {
  if (description) {
    ReactGA.exception({ description, fatal });
  }
};

gtag.js

export const GA_TRACKING_ID = '123456789'; // 9 digits format ?? it is correct key?


export const homepage = () => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: window.location.pathname,
  });
};

export const pageview = (url) => {
  window.gtag('config', GA_TRACKING_ID, {
    page_path: url,
  });
};

export const event = ({ action, category, label, value }) => {
  window.gtag('event', action, {
    event_category: category,
    event_label: label,
    value,
  });
};
4

0 回答 0