提交 8bf8c865 编写于 作者: J James Mosier 提交者: Luis Alvarez D

[example] Added AMP Google Analytics example (#9723)

* added AMP Google Analytics integration example

* added Amp custom element component w/ separate analytics component
上级 d0424d20
# Example app with google analytics & amp
## Deploy your own
Deploy the example using [ZEIT Now](https://zeit.co/now):
[![Deploy with ZEIT Now](https://zeit.co/button)](https://zeit.co/new/project?template=https://github.com/zeit/next.js/tree/canary/examples/with-google-analytics-amp)
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) to bootstrap the example:
```bash
npx create-next-app --example with-google-analytics-amp with-google-analytics-amp-app
# or
yarn create next-app --example with-google-analytics-amp with-google-analytics-amp-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-google-analytics-amp
cd with-google-analytics-amp
```
Install it and run:
```bash
yarn
yarn dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download)):
```bash
now
```
## The idea behind the example
This example shows how to use [Next.js](https://github.com/zeit/next.js) along with [Google Analytics](https://developers.google.com/analytics/devguides/collection/gtagjs/) in conjunction with [AMP](https://nextjs.org/docs#amp-support). A custom [\_document](https://github.com/zeit/next.js/#custom-document) is used to inject [tracking snippet](https://developers.google.com/analytics/devguides/collection/gtagjs/) and track [pageviews](https://developers.google.com/analytics/devguides/collection/gtagjs/pages) and [event](https://developers.google.com/analytics/devguides/collection/gtagjs/events). There are two separate initializations of the Google Analytics tracking code; one for AMP and one for non-AMP pages.
import React from 'react'
import Link from 'next/link'
export default () => (
<header>
<nav>
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/about">
<a>About</a>
</Link>
</li>
<li>
<Link href="/contact">
<a>Contact</a>
</Link>
</li>
</ul>
</nav>
</header>
)
import React from 'react'
import Header from './Header'
export default ({ children }) => (
<div>
<Header />
{children}
</div>
)
import React from 'react'
import AmpIncludeCustomElement from './AmpIncludeCustomElement'
export default props => (
<>
<AmpIncludeCustomElement name="amp-analytics" version="0.1" />
<amp-analytics type={props.type}>
{props.script && (
<script
type="application/json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(props.script),
}}
/>
)}
</amp-analytics>
</>
)
import React from 'react'
import Head from 'next/head'
export default props => (
<Head>
<script
async
custom-element={props.name}
src={
'https://cdn.ampproject.org/v0/' +
props.name +
'-' +
props.version +
'.js'
}
key={props.name}
/>
</Head>
)
export const GA_TRACKING_ID = '<YOUR_GA_TRACKING_ID>'
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
window.gtag('config', GA_TRACKING_ID, {
page_path: url,
})
}
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value,
})
}
{
"name": "with-google-analytics-amp",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0"
}
}
import App from 'next/app'
import Router from 'next/router'
import * as gtag from '../lib/gtag'
Router.events.on('routeChangeComplete', url => gtag.pageview(url))
export default App
import React from 'react'
import Document, { Main, NextScript } from 'next/document'
import { useAmp } from 'next/amp'
import { GA_TRACKING_ID } from '../lib/gtag'
import AmpAnalytics from '../components/amp/AmpAnalytics'
function AmpWrap({ ampOnly, nonAmp }) {
const isAmp = useAmp()
if (ampOnly) return isAmp && ampOnly
return !isAmp && nonAmp
}
export default class extends Document {
render() {
return (
<html>
<body>
<Main />
<NextScript />
{/* AMP - Google Analytics */}
<AmpWrap
ampOnly={
<AmpAnalytics
type="googleanalytics"
script={{
vars: {
account: GA_TRACKING_ID,
gtag_id: GA_TRACKING_ID,
config: {
[GA_TRACKING_ID]: { groups: 'default' },
},
},
triggers: {
trackPageview: {
on: 'visible',
request: 'pageview',
},
},
}}
/>
}
/>
{/* Non-AMP - Google Analytics */}
<AmpWrap
nonAmp={
<>
<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}');
`,
}}
/>
</>
}
/>
</body>
</html>
)
}
}
import React from 'react'
import Page from '../components/Page'
export default () => (
<Page>
<h1>This is the About page</h1>
</Page>
)
import React, { Component } from 'react'
import Page from '../components/Page'
import * as gtag from '../lib/gtag'
export default class extends Component {
state = { message: '' }
handleInput = e => {
this.setState({ message: e.target.value })
}
handleSubmit = e => {
e.preventDefault()
gtag.event({
action: 'submit_form',
category: 'Contact',
label: this.state.message,
})
this.setState({ message: '' })
}
render() {
return (
<Page>
<h1>This is the Contact page</h1>
<form onSubmit={this.handleSubmit}>
<label>
<span>Message:</span>
<textarea onChange={this.handleInput} value={this.state.message} />
</label>
<button type="submit">submit</button>
</form>
</Page>
)
}
}
import React from 'react'
import Page from '../components/Page'
export default () => (
<Page>
<h1>This is the Home page</h1>
</Page>
)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册