如何建立反应路由器谷歌分析?

我正在尝试在我的反应网站上建立谷歌分析,并且遇到了一些包,但是没有一个在例子方面有我所拥有的那种设置。希望有人能解释一下。

我看到的包裹是 反应

我在 index.js上的渲染方法如下所示。

React.render((
<Router history={createBrowserHistory()}>
<Route path="/" component={App}>
<IndexRoute component={Home} onLeave={closeHeader}/>
<Route path="/about" component={About} onLeave={closeHeader}/>
<Route path="/gallery" component={Gallery} onLeave={closeHeader}/>
<Route path="/contact-us" component={Contact} onLeave={closeHeader}>
<Route path="/contact-us/:service" component={Contact} onLeave={closeHeader}/>
</Route>
<Route path="/privacy-policy" component={PrivacyPolicy} onLeave={closeHeader} />
<Route path="/feedback" component={Feedback} onLeave={closeHeader} />
</Route>
<Route path="*" component={NoMatch} onLeave={closeHeader}/>
</Router>), document.getElementById('root'));
78911 次浏览

保留对历史对象的引用。

import { createBrowserHistory } from 'history';


var history = createBrowserHistory();


ReactDOM.render((
<Router history={history}>
[...]

然后添加一个监听器来记录每个页面视图。(这里假设您已经以通常的方式设置了 window.ga对象。)

history.listen((location) => {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
});

首先,在 index.js 中设置 onUpdate 函数来调用 ga

import ga from 'ga.js';
onUpdate() {
console.log('=====GA=====>', location.pathname);
console.log('=====GA_TRACKING_CODE=====>', GA_TRACKING_CODE);
ga("send", "pageview", location.pathname);
}


render() {
return (
<Router onUpdate={this.onUpdate.bind(this)}>...</Router>
);
}

还有 ga.js:

'use strict';
if(typeof window !== 'undefined' && typeof GA_TRACKING_CODE !== 'undefined') {
(function(window, document, script, url, r, tag, firstScriptTag) {
window['GoogleAnalyticsObject']=r;
window[r] = window[r] || function() {
(window[r].q = window[r].q || []).push(arguments)
};
window[r].l = 1*new Date();
tag = document.createElement(script),
firstScriptTag = document.getElementsByTagName(script)[0];
tag.async = 1;
tag.src = url;
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
})(
window,
document,
'script',
'//www.google-analytics.com/analytics.js',
'ga'
);


var ga = window.ga;


ga('create', GA_TRACKING_CODE, 'auto');


module.exports = function() {
return window.ga.apply(window.ga, arguments);
};
} else {
module.exports = function() {console.log(arguments)};
}

鉴于谷歌分析是加载和初始化的跟踪 ID。

Here is a solution for react-router version 4 using the <Route> component to track page views.

<Route path="/" render={({location}) => {
if (typeof window.ga === 'function') {
window.ga('set', 'page', location.pathname + location.search);
window.ga('send', 'pageview');
}
return null;
}} />

您只需在 <Router>中呈现这个组件(但不是作为 <Switch>的直接子组件)。

只要位置道具发生变化,就会重新呈现这个组件(实际上并没有呈现任何东西) ,从而触发页面视图。

如果你使用哈希或浏览器历史记录,你可以:

import trackingHit from 'tracking';


import { Router, browserHistory } from 'react-router';
browserHistory.listen(trackingHit);
// OR
import { Router, hashHistory } from 'react-router';
hashHistory.listen(trackingHit);

在哪里。/追踪。 es6

export default function(location) {
console.log('New page hit', location.pathname);
// Do your shizzle here
}

注意,如果使用 react-router-4中的 react-router-dom包,可以这样处理:

import { Router, Route } from 'react-router-dom';
import { createBrowserHistory } from 'history';


const history = createBrowserHistory();
const initGA = (history) => {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');


ga('create', 'YOUR_IDENTIFIER_HERE', 'auto');
ga('send', 'pageview');


history.listen((location) => {
console.log("tracking page view: " + location.pathname);
ga('send', 'pageview', location.pathname);
});
};


initGA(history);


class App extends Component { //eslint-disable-line
render() {
return
(<Router history={history} >
<Route exact path="/x" component={x} />
<Route exact path="/y" component={y} />
</Router>)
}
}

注意,这需要您安装 history包(npm install history)。这已经是一个反应路由器域的依赖项,所以您不需要在这里添加任何页面权重。

另请注意: 这是不可能使用的浏览器路由器组件和仪器,你的 ga 跟踪这种方式。这是可以的,因为 BrowserRouter 组件只是路由器对象的一个非常薄的包装器。我们在这里用 <Router history={history}>重新创建 BrowserRouter 功能,其中 const history = createBrowserHistory();

使用 index.js 实现基本的 response-ga

var ReactGA = require('react-ga'); // require the react-ga module
ReactGA.initialize('Your-UA-ID-HERE'); // add your UA code


function logPageView() { // add this function to your component
ReactGA.set({ page: window.location.pathname + window.location.search });
ReactGA.pageview(window.location.pathname + window.location.search);
}


React.render((
<Router history={createBrowserHistory()} onUpdate={logPageView} > // insert onUpdate props here
<Route path="/" component={App}>
<IndexRoute component={Home} onLeave={closeHeader}/>
<Route path="/about" component={About} onLeave={closeHeader}/>
<Route path="/gallery" component={Gallery} onLeave={closeHeader}/>
<Route path="/contact-us" component={Contact} onLeave={closeHeader}>
<Route path="/contact-us/:service" component={Contact} onLeave={closeHeader}/>
</Route>
<Route path="/privacy-policy" component={PrivacyPolicy} onLeave={closeHeader} />
<Route path="/feedback" component={Feedback} onLeave={closeHeader} />
</Route>
<Route path="*" component={NoMatch} onLeave={closeHeader} />
</Router>), document.getElementById('root'));

我正在使用 React 路由器 v4和 Google Analytics 全球网站标签,在撰写本文时,它似乎是推荐的。

我的解决办法是:

react-router-dom创建一个包装在 路由器中的组件:

import React from 'react';
import { withRouter } from 'react-router-dom';
import { GA_TRACKING_ID } from '../config';


class GoogleAnalytics extends React.Component {
componentWillUpdate ({ location, history }) {
const gtag = window.gtag;


if (location.pathname === this.props.location.pathname) {
// don't log identical link clicks (nav links likely)
return;
}


if (history.action === 'PUSH' &&
typeof(gtag) === 'function') {
gtag('config', GA_TRACKING_ID, {
'page_title': document.title,
'page_location': window.location.href,
'page_path': location.pathname
});
}
}


render () {
return null;
}
}


export default withRouter(GoogleAnalytics);

只需在你的路由器中添加组件(我相信在任何匹配的路由和任何 Switch 组件之后都是最理想的,因为分析功能不应该优先于你的站点渲染) :

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import IndexPage from './IndexPage';
import NotFoundPage from './NotFoundPage';
import GoogleAnalytics from './GoogleAnalytics';


const App = () => (
<Router>
<Switch>
<Route exact path="/" component={IndexPage} />
<Route component={NotFoundPage} />
</Switch>
<GoogleAnalytics />
</Router>
);

如上所述:

方法更改路由时,withRouter 将重新呈现其组件 和渲染道具一样的道具

因此,当路线改变时,GoogleAnalytics组件将更新,它将收到新的位置作为道具,和 history.action将或者 PUSH为一个新的历史项目或者 POP的信号向后通过历史(我认为不应该触发一个页面查看,但你可以调整在 componentWillUpdate中的如果语句,因为你认为合适(你甚至可以尝试 componentDidUpdatethis.props代替,但我不确定哪一个更好))。

我建议使用优秀的 react-router-ga包,它非常轻量级,而且易于配置,特别是在使用 BrowserRouter包装器时。

Import the component:

import Analytics from 'react-router-ga';

然后简单地在你的 BrowserRouter中添加 <Analytics>:

<BrowserRouter>
<Analytics id="UA-ANALYTICS-1">
<Switch>
<Route path="/somewhere" component={SomeComponent}/>
</Switch>
</Analytics>
</BrowserRouter>

总是按照图书馆推荐的方式去做

In the React-GA documentation, they have added a community component recommended for using with React Router: https://github.com/react-ga/react-ga/wiki/React-Router-v4-withTracker

Implementation

import withTracker from './withTracker';


ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Route component={withTracker(App, { /* additional attributes */ } )} />
</ConnectedRouter>
</Provider>,
document.getElementById('root'),
);

密码

import React, { Component, } from "react";
import GoogleAnalytics from "react-ga";


GoogleAnalytics.initialize("UA-0000000-0");


const withTracker = (WrappedComponent, options = {}) => {
const trackPage = page => {
GoogleAnalytics.set({
page,
...options,
});
GoogleAnalytics.pageview(page);
};


// eslint-disable-next-line
const HOC = class extends Component {
componentDidMount() {
// eslint-disable-next-line
const page = this.props.location.pathname + this.props.location.search;
trackPage(page);
}


componentDidUpdate(prevProps) {
const currentPage =
prevProps.location.pathname + prevProps.location.search;
const nextPage =
this.props.location.pathname + this.props.location.search;


if (currentPage !== nextPage) {
trackPage(nextPage);
}
}


render() {
return <WrappedComponent {...this.props} />;
}
};


return HOC;
};


export default withTracker;

这里有一个最简单的方法来跟踪所有的路径,其中包含一些变通方法:

npm i --save history react-ga

create a file history.js

import { createBrowserHistory } from "history"
import ReactGA from "react-ga"


ReactGA.initialize(process.env.REACT_APP_GA)


const history = createBrowserHistory()
history.listen((location) => {
ReactGA.pageview(location.pathname)
})


// workaround for initial visit
if (window.performance && (performance.navigation.type === performance.navigation.TYPE_NAVIGATE)) {
ReactGA.pageview("/")
}


export default history

然后将其导入到设置 Router的位置

import history from "./history"


...


class Route extends Component {
render() {
return (
<Router history={history}>
<Switch>
<Route path="/" exact component={HomePage} />
...
</Switch>
</Router>
)
}


export default Route

参考文献:

Gustavo Gonzalez | medium.com

历史 | GitHub

我建议使用 Segment 分析库并遵循 快速反应指南来使用 react-router库跟踪页面调用。您可以允许 <Route />组件在页面呈现时进行处理,并使用 componentDidMount调用 page调用。下面的例子展示了一种方法:

    const App = () => (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
);


export default App;
    export default class Home extends Component {
componentDidMount() {
window.analytics.page('Home');
}


render() {
return (
<h1>
Home page.
</h1>
);
}
}

我是 https://github.com/segmentio/analytics-react的维护者。使用 Segment,如果你有兴趣尝试多种分析工具(我们支持超过250个目的地) ,你可以通过打开开关来切换不同的目的地,而不需要编写任何额外的代码。

我喜欢马克•托马斯•穆勒(Mark Thomas Müller)对 给你的建议:

In your Index.js

import ReactGA from 'react-ga'


ReactGA.initialize('YourAnalyticsID')


ReactDOM.render(<App />, document.getElementById('root'))

Where your routes are:

import React, { Component } from 'react'
import { Router, Route } from 'react-router-dom'
import createHistory from 'history/createBrowserHistory'
import ReactGA from 'react-ga'


const history = createHistory()
history.listen(location => {
ReactGA.set({ page: location.pathname })
ReactGA.pageview(location.pathname)
})


export default class AppRoutes extends Component {
componentDidMount() {
ReactGA.pageview(window.location.pathname)
}


render() {
return (
<Router history={history}>
<div>
<Route path="/your" component={Your} />
<Route path="/pages" component={Pages} />
<Route path="/here" component={Here} />
</div>
</Router>
)
}
}

简短、可伸缩和简单:)

根据@david-l-walsh 和@bozdoz 的建议

我创建了一个 HOC,执行 window.ga('set','page','{currentUrl})window.ga('send', 'pageview');函数,并很容易在路由器页面直接使用..。

这就是 HOC:

import React from 'react';
import { history } from '../../store'; // or wherever you createBrowserHistory(); invokation is


function withGAHistoryTrack(WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
}


componentDidMount() {
const { location } = history;
const page = location.pathname + location.search;


if (typeof window.ga === 'function') {
window.ga('set', 'page', page);
window.ga('send', 'pageview');
}
}


render() {
return <WrappedComponent {...this.props} />;
}
};
}


export default withGAHistoryTrack;

并在路由器页面中以这种方式使用:

<Route
path={'yourPath'}
component={withGAHistoryTrack(yourComponent)}
exact
/>

对于在某些事件(如 onClick 等)上动态更新 url,可以使用以下方法:

 //Imports
import ReactGA from "react-ga";
import { createBrowserHistory } from "history";


// Add following on some event, like onClick (depends on your requirement)
const history = createBrowserHistory();
ReactGA.initialize("<Your-UA-ID-HERE>");
ReactGA.pageview(history.location.pathname);

这个问题是关于 react-ga,但这个软件包将很快过时,因为它的 doesn't support谷歌分析4。下面是一个使用任何库或本机 gtag的通用解决方案。加上 GA4反应看看这个答案: https://stackoverflow.com/a/73354959/2771889

由于 react-router v5.1.0可以很容易地解决这个问题与 useLocation

usePageTracking.js

import { useEffect} from "react";
import { useLocation } from "react-router-dom";


const usePageTracking = () => {
const location = useLocation();


useEffect(() => {
// track pageview with gtag / react-ga / react-ga4, for example:
window.gtag("event", "page_view", {
page_path: location.pathname + location.search,
});
}, [location]);
};


export default usePageTracking;

App.js

const App = () => {
usePageTracking();


return (...);
};

请记住,GoogleAnalytics 可以自动跟踪页面,但这并不适用于每个用例。例如,hashsearch参数的更改是 没被追踪。这会导致很多混乱。例如,当使用 HashRouter或锚链接时,将不会跟踪导航。要完全控制页面查看跟踪,可以使用 关闭自动跟踪系统。请参阅详细说明: The Ultimate Guide to Google Analytics (UA & GA4) on React (Or Anything Else

你可以看到这个工作在 打字机打字机打字机打字机,我正在使用它与 GA4。