Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

README.md 20KB

před 3 roky
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. # react-ga
  2. ### React Google Analytics Module
  3. [![Build Status](https://img.shields.io/travis/react-ga/react-ga/master.svg?style=flat-square)](https://travis-ci.org/react-ga/react-ga)
  4. [![npm version](https://img.shields.io/npm/v/react-ga.svg?style=flat-square)](https://www.npmjs.com/package/react-ga)
  5. [![npm downloads](https://img.shields.io/npm/dm/react-ga.svg?style=flat-square)](https://www.npmjs.com/package/react-ga)
  6. This is a JavaScript module that can be used to include Google Analytics tracking code in a website or app that uses [React](https://facebook.github.io/react/) for its front-end codebase. It does not currently use any React code internally, but has been written for use with a number of Mozilla Foundation websites that are using React, as a way to standardize our GA Instrumentation across projects.
  7. It is designed to work with [Universal Analytics](https://support.google.com/analytics/answer/2790010) and will not support the older `ga.js` implementation.
  8. This module is mildly opinionated in how we instrument tracking within our front-end code. Our API is slightly more verbose than the core Google Analytics library, in the hope that the code is easier to read and understand for our engineers. See examples below.
  9. If you use `react-ga` too, we'd love your feedback. Feel free to file [issues, ideas and pull requests against this repo](https://github.com/react-ga/react-ga/issues).
  10. ## Installation
  11. With [npm](https://www.npmjs.com/):
  12. ```bash
  13. npm install react-ga --save
  14. ```
  15. With [bower](http://bower.io/):
  16. ```bash
  17. bower install react-ga --save
  18. ```
  19. Note that [React](https://github.com/facebook/react) >= 0.14.0 is needed in order to use the `<OutboundLink>` component.
  20. ## Usage
  21. ### With npm
  22. Initializing GA and Tracking Pageviews:
  23. ```js
  24. import ReactGA from 'react-ga';
  25. ReactGA.initialize('UA-000000-01');
  26. ReactGA.pageview(window.location.pathname + window.location.search);
  27. ```
  28. ### With bower
  29. When included as a script tag, a variable `ReactGA` is exposed in the global scope.
  30. ```js
  31. <!-- The core React library -->
  32. <script src="https://unpkg.com/react@15.5.0/dist/react.min.js"></script>
  33. <!-- The ReactDOM Library -->
  34. <script src="https://unpkg.com/react-dom@15.5.0/dist/react-dom.min.js"></script>
  35. <!-- ReactGA library -->
  36. <script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script>
  37. <script>
  38. ReactGA.initialize('UA-000000-01', { debug: true });
  39. </script>
  40. ```
  41. ### Demo Code
  42. For a working demo have a look at the [demo files](/demo) or clone this repo and run `npm install` `npm start` then open http://localhost:8080 and follow the instructions.
  43. Demo requires you to have your own TrackingID.
  44. ## Upgrading from `1.x` to `2.x`
  45. You can safely upgrade to `2.x` as there are no breaking changes. The main new feature is that the underlying `ga` function is now exposed via the property `ReactGA.ga`. This can be helpful when you need a function that `ReactGA` doesn't support at the moment. Also, for that reason, it is recommended that you rename your imported value as `ReactGA` rather than `ga` so as to distinguish between the React GA wrapper and the original `ga` function.
  46. ## Community Components
  47. While some convenience components are included inside the package, some are specific to each application.
  48. A community curated list of these is available in the wiki: https://github.com/react-ga/react-ga/wiki/Community-Components. Feel free to add any you have found useful.
  49. ## API
  50. #### ReactGA.initialize(gaTrackingID, options)
  51. GA must be initialized using this function before any of the other tracking functions will record any data. The values are checked and sent through to the `ga('create', ...` call.
  52. If you aren't getting any data back from Page Timings, you may have to add `siteSpeedSampleRate: 100` to the `gaOptions` object. This will send 100% of hits to Google Analytics. By default only 1% are sent.
  53. ###### Example
  54. ```js
  55. ReactGA.initialize('UA-000000-01', {
  56. debug: true,
  57. titleCase: false,
  58. gaOptions: {
  59. userId: 123
  60. }
  61. });
  62. ```
  63. Or with multiple trackers
  64. ```js
  65. ReactGA.initialize(
  66. [
  67. {
  68. trackingId: 'UA-000000-01',
  69. gaOptions: {
  70. name: 'tracker1',
  71. userId: 123
  72. }
  73. },
  74. {
  75. trackingId: 'UA-000000-02',
  76. gaOptions: { name: 'tracker2' }
  77. }
  78. ],
  79. { debug: true, alwaysSendToDefaultTracker: false }
  80. );
  81. ```
  82. | Value | Notes |
  83. | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  84. | gaTrackingID | `String`. Required. GA Tracking ID like `UA-000000-01`. |
  85. | options.debug | `Boolean`. Optional. If set to `true`, will output additional feedback to the console. |
  86. | options.titleCase | `Boolean`. Optional. Defaults to `true`. If set to `false`, strings will not be converted to title case before sending to GA. |
  87. | options.gaOptions | `Object`. Optional. [GA configurable create only fields.](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference) |
  88. | options.gaAddress | `String`. Optional. If you are self-hosting your `analytics.js`, you can specify the URL for it here. |
  89. | options.alwaysSendToDefaultTracker | `Boolean`. Optional. Defaults to `true`. If set to `false` _and_ using multiple trackers, the event will not be send to the default tracker. |
  90. | options.testMode | `Boolean`. Optional. Defaults to `false`. Enables test mode. See [here](https://github.com/react-ga/react-ga#test-mode) for more information. |
  91. | options.standardImplementation | `Boolean`. Optional. Defaults to `false`. Enables loading GA as google expects it. See [here](https://github.com/react-ga/react-ga#standard-implementation) for more information. |
  92. | options.useExistingGa | `Boolean`. Optional. Skips call to `window.ga()`, assuming you have manually run it. |
  93. | options.redactEmail | `Boolean`. Optional. Defaults to `true`. Enables redacting a email as the string that in "Event Category" and "Event Action". |
  94. If you are having additional troubles and setting `debug = true` shows as working please try using the [Chrome GA Debugger Extension](https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna).
  95. This will help you figure out if your implementation is off or your GA Settings are not correct.
  96. #### ReactGA.set(fieldsObject)
  97. This will set the values of [custom dimensions](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#dimension) in Google Analytics.
  98. ###### Example
  99. ```js
  100. ReactGA.set({ dimension14: 'Sports' });
  101. ```
  102. Or with multiple trackers
  103. ```js
  104. ReactGA.set({ userId: 123 }, ['tracker2']);
  105. ```
  106. | Value | Notes |
  107. | ------------ | ----------------------------------------------------------------- |
  108. | fieldsObject | `Object`. e.g. `{ userId: 123 }` |
  109. | trackerNames | `Array`. Optional. A list of extra trackers to run the command on |
  110. #### ReactGA.pageview(path)
  111. ###### Example
  112. ```js
  113. ReactGA.pageview('/about/contact-us');
  114. ```
  115. Or with multiple trackers
  116. ```js
  117. ReactGA.pageview('/about/contact-us', ['tracker2']);
  118. ```
  119. This will send all the named trackers listed in the array parameter. The default tracker will or will not send according to the `initialize()` setting `alwaysSendToDefaultTracker` (defaults to `true` if not provided).
  120. | Value | Notes |
  121. | ------------ | ----------------------------------------------------------------- |
  122. | path | `String`. e.g. '/get-involved/other-ways-to-help' |
  123. | trackerNames | `Array`. Optional. A list of extra trackers to run the command on |
  124. | title | `String`. Optional. e.g. 'Other Ways to Help' |
  125. See example above for use with `react-router`.
  126. #### ReactGA.modalview(modalName)
  127. A modal view is often an equivalent to a pageview in our UX, but without a change in URL that would record a standard GA pageview. For example, a 'contact us' modal may be accessible from any page in a site, even if we don't have a standalone 'contact us' page on its own URL. In this scenario, the modalview should be recorded using this function.
  128. ###### Example
  129. ```js
  130. ReactGA.modalview('/about/contact-us');
  131. ```
  132. | Value | Notes |
  133. | --------- | --------------------------------------------------- |
  134. | modalName | `String`. E.g. 'login', 'read-terms-and-conditions' |
  135. #### ReactGA.event(args)
  136. Tracking in-page `event` interactions is key to understanding the use of any interactive web property. This is how we record user interactions that don't trigger a change in URL.
  137. ###### Examples
  138. ```js
  139. ReactGA.event({
  140. category: 'User',
  141. action: 'Created an Account'
  142. });
  143. ReactGA.event({
  144. category: 'Social',
  145. action: 'Rated an App',
  146. value: 3
  147. });
  148. ReactGA.event({
  149. category: 'Editing',
  150. action: 'Deleted Component',
  151. label: 'Game Widget'
  152. });
  153. ReactGA.event({
  154. category: 'Promotion',
  155. action: 'Displayed Promotional Widget',
  156. label: 'Homepage Thing',
  157. nonInteraction: true
  158. });
  159. ```
  160. | Value | Notes |
  161. | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
  162. | args.category | `String`. Required. A top level category for these events. E.g. 'User', 'Navigation', 'App Editing', etc. |
  163. | args.action | `String`. Required. A description of the behaviour. E.g. 'Clicked Delete', 'Added a component', 'Deleted account', etc. |
  164. | args.label | `String`. Optional. More precise labelling of the related action. E.g. alongside the 'Added a component' action, we could add the name of a component as the label. E.g. 'Survey', 'Heading', 'Button', etc. |
  165. | args.value | `Int`. Optional. A means of recording a numerical value against an event. E.g. a rating, a score, etc. |
  166. | args.nonInteraction | `Boolean`. Optional. If an event is not triggered by a user interaction, but instead by our code (e.g. on page load), it should be flagged as a `nonInteraction` event to avoid skewing bounce rate data. |
  167. | args.transport | `String`. Optional. This specifies the transport mechanism with which hits will be sent. Valid values include 'beacon', 'xhr', or 'image'. |
  168. #### ReactGA.timing(args)
  169. Allow to measure periods of time such as AJAX requests and resources loading by sending hits using the analytics.js library. For more detailed description, please refer to https://developers.google.com/analytics/devguides/collection/analyticsjs/user-timings.
  170. ###### Example
  171. Usage:
  172. ```js
  173. ReactGA.timing({
  174. category: 'JS Libraries',
  175. variable: 'load',
  176. value: 20, // in milliseconds
  177. label: 'CDN libs'
  178. });
  179. ```
  180. This is equivalent to the following Google Analytics command:
  181. ```js
  182. ga('send', 'timing', 'JS Libraries', 'load', 20, 'CDN libs');
  183. ```
  184. | Value | Notes |
  185. | ------------- | ------------------------------------------------------------------------------------------------- |
  186. | args.category | `String`. Required. A string for categorizing all user timing variables into logical groups. |
  187. | args.variable | `String`. Required. Name of the variable being recorded. |
  188. | args.value | `Int`. Required. Number of milliseconds elapsed time to report. |
  189. | args.label | `String`. Optional. It can be used to add flexibility in visualizing user timings in the reports. |
  190. #### ReactGA.ga()
  191. The original `ga` function can be accessed via this method. This gives developers the flexibility of directly
  192. using `ga.js` features that have not yet been implemented in `ReactGA`. No validations will be done
  193. by `ReactGA` as it is being bypassed if this approach is used.
  194. If no arguments are passed to `ReactGA.ga()`, the `ga` object is returned instead.
  195. ###### Example
  196. Usage with arguments:
  197. ```js
  198. ReactGA.ga('send', 'pageview', '/mypage');
  199. ```
  200. Usage without arguments:
  201. ```js
  202. var ga = ReactGA.ga();
  203. ga('send', 'pageview', '/mypage');
  204. ```
  205. #### ReactGA.outboundLink(args, hitCallback)
  206. Tracking links out to external URLs (including id.webmaker.org for OAuth 2.0 login flow). A declarative approach is found in the next section, by using an `<OutboundLink>` component.
  207. ###### Example
  208. ```js
  209. ReactGA.outboundLink(
  210. {
  211. label: 'Clicked Create an Account'
  212. },
  213. function () {
  214. console.log('redirect here');
  215. },
  216. ['tracker2']
  217. );
  218. ```
  219. | Value | Notes |
  220. | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  221. | args.label | `String`. Required. Description of where the outbound link points to. Either as a URL, or a string. |
  222. | hitCallback | `function`. The react-ga implementation accounts for the possibility that GA servers are down, or GA is blocked, by using a fallback 250ms timeout. See [notes in GA Dev Guide](https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#hitCallback) |
  223. | trackerNames | `Array<String>` Optional. A list of extra trackers to run the command on. |
  224. ### `<OutboundLink>` Component
  225. Outbound links can directly be used as a component in your React code and the event label will be sent directly to ReactGA.
  226. ###### Example
  227. ```js
  228. var ReactGA = require('react-ga');
  229. render() {
  230. return (
  231. <div>
  232. <ReactGA.OutboundLink
  233. eventLabel="myLabel"
  234. to="http://www.example.com"
  235. target="_blank"
  236. trackerNames={['tracker2']}
  237. >
  238. My Link
  239. </ReactGA.OutboundLink>
  240. </div>
  241. );
  242. }
  243. ```
  244. | Value | Notes |
  245. | ------------ | --------------------------------------------------------------------------------------------------- |
  246. | eventLabel | `String`. Required. Description of where the outbound link points to. Either as a URL, or a string. |
  247. | to | `String`. Required. URL the link leads to. |
  248. | target | `String`. Optional. To open the link in a new tab, use a value of `_blank`. |
  249. | trackerNames | `Array<String>` Optional. A list of extra trackers to run the command on. |
  250. For bower, use the `<ReactGA.OutboundLink>` component.
  251. #### ReactGA.exception(args)
  252. [GA exception tracking](https://developers.google.com/analytics/devguides/collection/analyticsjs/exceptions)
  253. ###### Example
  254. ```js
  255. ReactGA.exception({
  256. description: 'An error occurred',
  257. fatal: true
  258. });
  259. ```
  260. | Value | Notes |
  261. | ---------------- | -------------------------------------------------------------- |
  262. | args.description | `String`. Optional. Description of what happened. |
  263. | args.fatal | `boolean`. Optional. Set to `true` if it was a fatal exception. |
  264. #### ReactGA.plugin.require(name, [options])
  265. Require GA plugins.
  266. ###### Example
  267. ```js
  268. ReactGA.plugin.require('localHitSender', { path: '/log', debug: true });
  269. ```
  270. | Value | Notes |
  271. | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
  272. | name | `String`. Required. The name of the plugin to be required. Note: if the plugin is not an official analytics.js plugin, it must be provided elsewhere on the page. |
  273. | options | `Object`. Optional. An initialization object that will be passed to the plugin constructor upon instantiation. |
  274. #### ReactGA.plugin.execute(pluginName, action, [actionType], [payload])
  275. Execute the `action` for the `pluginName` with the payload.
  276. ###### Example
  277. ```js
  278. ReactGA.plugin.execute('ecommerce', 'addTransaction', {
  279. id: 'jd38je31j',
  280. revenue: '3.50'
  281. });
  282. ```
  283. You can use this function with four arguments to pass `actionType` and `payload` along with executed action
  284. ###### Example
  285. ```js
  286. ReactGA.plugin.execute('ec', 'setAction', 'purchase', {
  287. id: 'jd38je31j',
  288. revenue: '3.50'
  289. });
  290. ```
  291. ### Test Mode
  292. To enable test mode, initialize ReactGA with the `testMode: true` option. Here's an example from `tests/utils/testMode.test.js`
  293. ```js
  294. // This should be part of your setup
  295. ReactGA.initialize('foo', { testMode: true });
  296. // This would be in the component/js you are testing
  297. ReactGA.ga('send', 'pageview', '/mypage');
  298. // This would be how you check that the calls are made correctly
  299. expect(ReactGA.testModeAPI.calls).toEqual([
  300. ['create', 'foo', 'auto'],
  301. ['send', 'pageview', '/mypage']
  302. ]);
  303. ```
  304. ### Standard Implementation
  305. To enable standard implemention of google analytics.
  306. Add this script to your html
  307. ```html
  308. <!-- Google Analytics -->
  309. <script>
  310. (function (i, s, o, g, r, a, m) {
  311. i['GoogleAnalyticsObject'] = r;
  312. (i[r] =
  313. i[r] ||
  314. function () {
  315. (i[r].q = i[r].q || []).push(arguments);
  316. }),
  317. (i[r].l = 1 * new Date());
  318. (a = s.createElement(o)), (m = s.getElementsByTagName(o)[0]);
  319. a.async = 1;
  320. a.src = g;
  321. m.parentNode.insertBefore(a, m);
  322. })(
  323. window,
  324. document,
  325. 'script',
  326. '<%=htmlWebpackPlugin.options.analyticsURL%>',
  327. 'ga'
  328. );
  329. ga('create', 'UA-XXX-X', 'auto');
  330. ga('send', 'pageview');
  331. </script>
  332. <!-- End Google Analytics -->
  333. ```
  334. Initialize ReactGA with `standardImplementation: true` option.
  335. ```js
  336. // This should be part of your setup
  337. ReactGA.initialize('UA-XXX-X', { standardImplementation: true });
  338. ```
  339. ---
  340. ## Development
  341. ### Prerequisites
  342. - node.js
  343. - npm
  344. - `npm install`
  345. - `npm install react@^15.6.1 prop-types@^15.5.10` - This is for the optional dependencies.
  346. ### To Test
  347. ```bash
  348. npm test
  349. ```
  350. ### Submitting changes/fixes
  351. Follow instructions inside [CONTRIBUTING.md](https://github.com/react-ga/react-ga/blob/master/CONTRIBUTING.md)
  352. ---
  353. #### Acknowledgements
  354. - Quite a lot of the code in this repo, came from [webmaker-analytics](https://github.com/mozilla/webmaker-analytics).