#google-analytics #next.js #gtag.js #react-ga
#google-аналитика #next.js #gtag.js #реагировать-га
Вопрос:
В моем проекте Nextjs(Nextjs v10) по просьбе владельца используются 2 аналитики. Изначально это была просто Google analytics, позже был добавлен gtag.
Все манипуляции, которые я пробую в последнее время, не включают gtag, но иногда они влияют на google-аналитику, увеличивая отскок.
_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) =gt; { // call previously defined callback if is a function if (typeof previousCallback === 'function') previousCallback(); logPageView(); url amp;amp; 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 ( lt;Htmlgt; lt;Headgt; ... lt;script async src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}/gt; lt;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, }); `, }} /gt; lt;/Headgt; lt;/Htmlgt; ) } }
analytics.js
import ReactGA from 'react-ga'; export const GA_ID = 'UA-XXXXXXXX-1'; export const initGA = () =gt; { ReactGA.initialize(GA_ID, { // debug: true, }); }; export const logPageView = () =gt; { ReactGA.set({ page: window.location.pathname }); ReactGA.pageview(window.location.pathname); }; export const logEvent = (category = '', action = '') =gt; { if (category amp;amp; action) { ReactGA.event({ category, action }); } }; export const logException = (description = '', fatal = false) =gt; { if (description) { ReactGA.exception({ description, fatal }); } };
gtag.js
export const GA_TRACKING_ID = '123456789'; // 9 digits format ?? it is correct key? export const homepage = () =gt; { window.gtag('config', GA_TRACKING_ID, { page_path: window.location.pathname, }); }; export const pageview = (url) =gt; { window.gtag('config', GA_TRACKING_ID, { page_path: url, }); }; export const event = ({ action, category, label, value }) =gt; { window.gtag('event', action, { event_category: category, event_label: label, value, }); };