-
Notifications
You must be signed in to change notification settings - Fork 10.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add gatsby-plugin-google-gtag #9032
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"presets": [ | ||
["../../.babel-preset.js", { "browser": true }] | ||
] | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/*.js |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# Logs | ||
logs | ||
*.log | ||
|
||
# Runtime data | ||
pids | ||
*.pid | ||
*.seed | ||
|
||
# Directory for instrumented libs generated by jscoverage/JSCover | ||
lib-cov | ||
|
||
# Coverage directory used by tools like istanbul | ||
coverage | ||
|
||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) | ||
.grunt | ||
|
||
# node-waf configuration | ||
.lock-wscript | ||
|
||
# Compiled binary addons (http://nodejs.org/api/addons.html) | ||
build/Release | ||
|
||
# Dependency directory | ||
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git | ||
node_modules | ||
*.un~ | ||
yarn.lock | ||
src | ||
flow-typed | ||
coverage | ||
decls | ||
examples |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
# gatsby-plugin-google-gtag | ||
|
||
Easily add Google Global Site Tag to your Gatsby site. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Sorta tangential to this PR, but could be helpful to document/link to why here, e.g. why this over gatsby-plugin-google-analytics |
||
|
||
## Install | ||
|
||
`npm install --save gatsby-plugin-google-gtag` | ||
|
||
## How to use | ||
|
||
```js | ||
// In your gatsby-config.js | ||
module.exports = { | ||
plugins: [ | ||
{ | ||
resolve: `gatsby-plugin-google-gtag`, | ||
options: { | ||
// You can add multiple tracking ids and a pageview event will be fired for all of them. | ||
trackingIds: [ | ||
'GA-TRACKING_ID', // Google Analytics / GA | ||
'AW-CONVERSION_ID', // Google Ads / Adwords / AW | ||
'DC-FLOODIGHT_ID', // Marketing Platform advertising products (Display & Video 360, Search Ads 360, and Campaign Manager) | ||
], | ||
// This object gets passed directly to the gtag config command | ||
// This config will be shared accross all trackingIds | ||
gtagConfig: { | ||
optimize_id: 'OPT_CONTAINER_ID', | ||
anonymize_ip: true, | ||
}, | ||
// This object is used for configuration specific to this plugin | ||
pluginConfig: { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @pieh do we have a standard for this? i.e. plugin specific options that are separate from the service you're configuring? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. AFAIK there is no convention for that, it's totally up to plugins. In this instance I'm not sure if there is value in grouping those settings in |
||
// Puts tracking script in the head instead of the body | ||
head: false, | ||
// Setting this parameter is also optional | ||
respectDNT: true, | ||
// Avoids sending pageview hits from custom paths | ||
exclude: ['/preview/**', '/do-not-track/me/too/'], | ||
}, | ||
}, | ||
}, | ||
], | ||
} | ||
``` | ||
|
||
## Custom Events | ||
|
||
This plugin automatically sends a "pageview" event to all products given as "trackingIds" on every Gatsbys route change. | ||
|
||
If you want to call a custom event you have access to `window.gtag` where you can call an event for all products: | ||
|
||
```js | ||
window.gtag('event', 'click', { ...data }); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Might want to reference that this needs to be guarded against for SSR, e.g. typeof window !== 'undefined' && window.gtag('event', 'click', {...data}) |
||
``` | ||
|
||
or you can target a specific product: | ||
|
||
```js | ||
window.gtag('event', 'click', { send_to: 'AW-CONVERSION_ID', ...data }); | ||
``` | ||
|
||
In either case don't forget to guard against SSR: | ||
|
||
```js | ||
typeof window !== 'undefined' && window.gtag('event', 'click', {...data); | ||
``` | ||
|
||
## `<OutboundLink>` component | ||
|
||
To make it easy to track clicks on outbound links the plugin provides a component. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure if it's worth calling this ExternalLink, instead of OutboundLink? Is Outbound a term used by gtag? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I agree with you, but it is already a gtag term https://support.google.com/analytics/answer/7478520?hl=en |
||
|
||
To use it, simply import it and use it like you would the `<a>` element e.g. | ||
|
||
```jsx | ||
import React from 'react'; | ||
import { OutboundLink } from 'gatsby-plugin-google-gtag' | ||
|
||
export default () => { | ||
<div> | ||
<OutboundLink | ||
href="https://www.gatsbyjs.org/packages/gatsby-plugin-google-gtag/" | ||
> | ||
Visit the Google Global Site Tag plugin page! | ||
</OutboundLink> | ||
</div> | ||
} | ||
``` | ||
|
||
## The "gtagConfig.anonymize_ip" option | ||
|
||
Some countries (such as Germany) require you to use the | ||
[\_anonymizeIP](https://support.google.com/analytics/answer/2763052) function for | ||
Google Site Tag. Otherwise you are not allowed to use it. The option adds the | ||
block of code below: | ||
|
||
```js | ||
function gaOptout() { | ||
;(document.cookie = | ||
disableStr + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/'), | ||
(window[disableStr] = !0) | ||
} | ||
|
||
var gaProperty = 'UA-XXXXXXXX-X', | ||
disableStr = 'ga-disable-' + gaProperty | ||
document.cookie.indexOf(disableStr + '=true') > -1 && (window[disableStr] = !0) | ||
``` | ||
|
||
If your visitors should be able to set an Opt-Out-Cookie (No future tracking) | ||
you can set a link e.g. in your imprint as follows: | ||
|
||
`<a href="javascript:gtagOptout();">Deactive Google Tracking</a>` | ||
|
||
## The "pluginConfig.respectDNT" option | ||
|
||
If you enable this optional option, Google Global Site Tag will not be loaded at all for visitors that have "Do Not Track" enabled. While using Google Global Site Tag does not necessarily constitute Tracking, you might still want to do this to cater to more privacy oriented users. | ||
|
||
## The "pluginConfig.exclude" option | ||
|
||
If you need to exclude any path from the tracking system, you can add it (one or more) to this optional array as glob expressions. | ||
|
||
## The "gtagConfig.optimize_id" option | ||
|
||
If you need to use Google Optimize for A/B testing, you can add this optional Optimize container id to allow Google Optimize to load the correct test parameters for your site. |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
{ | ||
"name": "gatsby-plugin-google-gtag", | ||
"description": "Gatsby plugin to add google gtag onto a site", | ||
"version": "1.0.0-beta.0", | ||
"author": "Tyler Buchea <tyler@buchea.com>", | ||
"bugs": { | ||
"url": "https://github.com/gatsbyjs/gatsby/issues" | ||
}, | ||
"dependencies": { | ||
"@babel/runtime": "^7.0.0", | ||
"minimatch": "^3.0.4" | ||
}, | ||
"devDependencies": { | ||
"@babel/cli": "^7.0.0", | ||
"@babel/core": "^7.0.0", | ||
"cross-env": "^5.1.4" | ||
}, | ||
"homepage": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-google-gtag#readme", | ||
"keywords": [ | ||
"gatsby", | ||
"gatsby-plugin", | ||
"google gtag", | ||
"google global site tag" | ||
], | ||
"license": "MIT", | ||
"main": "index.js", | ||
"peerDependencies": { | ||
"gatsby": ">2.0.0-alpha" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Probably just bump this to 2.0.0! |
||
}, | ||
"repository": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-google-gtag", | ||
"scripts": { | ||
"build": "babel src --out-dir . --ignore **/__tests__", | ||
"prepare": "cross-env NODE_ENV=production npm run build", | ||
"watch": "babel -w src --out-dir . --ignore **/__tests__" | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
export const onRouteUpdate = function({ location }) { | ||
if (process.env.NODE_ENV !== `production` || typeof gtag !== `function`) { | ||
return null | ||
} | ||
|
||
const pathIsExcluded = | ||
location && | ||
typeof window.excludeGtagPaths !== `undefined` && | ||
window.excludeGtagPaths.some(rx => rx.test(location.pathname)) | ||
|
||
if (pathIsExcluded) return null | ||
|
||
const pagePath = location | ||
? location.pathname + location.search + location.hash | ||
: undefined | ||
window.gtag(`event`, `page_view`, { page_path: pagePath }) | ||
|
||
return null | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import React from "react" | ||
import { Minimatch } from "minimatch" | ||
|
||
export const onRenderBody = ( | ||
{ setHeadComponents, setPostBodyComponents }, | ||
pluginOptions | ||
) => { | ||
if (process.env.NODE_ENV !== `production`) return null | ||
|
||
const firstTrackingId = | ||
pluginOptions.trackingIds && pluginOptions.trackingIds.length | ||
? pluginOptions.trackingIds[0] | ||
: `` | ||
|
||
const excludeGtagPaths = [] | ||
if (typeof pluginOptions.pluginConfig.exclude !== `undefined`) { | ||
pluginOptions.pluginConfig.exclude.map(exclude => { | ||
const mm = new Minimatch(exclude) | ||
excludeGtagPaths.push(mm.makeRe()) | ||
}) | ||
} | ||
|
||
const setComponents = pluginOptions.pluginConfig.head | ||
? setHeadComponents | ||
: setPostBodyComponents | ||
|
||
const renderHtml = () => ` | ||
${ | ||
excludeGtagPaths.length | ||
? `window.excludeGtagPaths=[${excludeGtagPaths.join(`,`)}];` | ||
: `` | ||
} | ||
${ | ||
typeof pluginOptions.gtagConfig.anonymize_ip !== `undefined` && | ||
pluginOptions.gtagConfig.anonymize_ip === true | ||
? `function gaOptout(){document.cookie=disableStr+'=true; expires=Thu, 31 Dec 2099 23:59:59 UTC;path=/',window[disableStr]=!0}var gaProperty='${firstTrackingId}',disableStr='ga-disable-'+gaProperty;document.cookie.indexOf(disableStr+'=true')>-1&&(window[disableStr]=!0);` | ||
: `` | ||
} | ||
if(${ | ||
typeof pluginOptions.respectDNT !== `undefined` && | ||
pluginOptions.respectDNT === true | ||
? `!(navigator.doNotTrack == "1" || window.doNotTrack == "1")` | ||
: `true` | ||
}) { | ||
window.dataLayer = window.dataLayer || []; | ||
function gtag(){dataLayer.push(arguments);} | ||
gtag('js', new Date()); | ||
|
||
${pluginOptions.trackingIds | ||
.map( | ||
trackingId => | ||
`gtag('config', '${trackingId}', ${JSON.stringify( | ||
pluginOptions.gtagConfig || {} | ||
)});` | ||
) | ||
.join(``)} | ||
} | ||
` | ||
|
||
return setComponents([ | ||
<script | ||
key={`gatsby-plugin-google-gtag`} | ||
async | ||
src={`https://www.googletagmanager.com/gtag/js?id=${firstTrackingId}`} | ||
/>, | ||
<script | ||
key={`gatsby-plugin-google-gtag-config`} | ||
dangerouslySetInnerHTML={{ __html: renderHtml() }} | ||
/>, | ||
]) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import React from "react" | ||
import PropTypes from "prop-types" | ||
|
||
function OutboundLink(props) { | ||
return ( | ||
<a | ||
{...props} | ||
onClick={e => { | ||
if (typeof props.onClick === `function`) { | ||
props.onClick() | ||
} | ||
let redirect = true | ||
if ( | ||
e.button !== 0 || | ||
e.altKey || | ||
e.ctrlKey || | ||
e.metaKey || | ||
e.shiftKey || | ||
e.defaultPrevented | ||
) { | ||
redirect = false | ||
} | ||
if (props.target && props.target.toLowerCase() !== `_self`) { | ||
redirect = false | ||
} | ||
if (window.gtag) { | ||
window.gtag(`event`, `click`, { | ||
event_category: `outbound`, | ||
event_label: props.href, | ||
transport_type: redirect ? `beacon` : ``, | ||
event_callback: function() { | ||
if (redirect) { | ||
document.location = props.href | ||
} | ||
}, | ||
}) | ||
} else { | ||
if (redirect) { | ||
document.location = props.href | ||
} | ||
} | ||
|
||
return false | ||
}} | ||
/> | ||
) | ||
} | ||
|
||
OutboundLink.propTypes = { | ||
href: PropTypes.string, | ||
target: PropTypes.string, | ||
onClick: PropTypes.func, | ||
} | ||
|
||
export { OutboundLink } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What about removing all the comments and sort the directories..?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This comes from package template - https://github.com/gatsbyjs/gatsby/blob/master/plop-templates/package/.npmignore.hbs it doesn't hurt to have comments here as this is mostly setup once and forget