Skip to content

Commit

Permalink
docs: add react, vue, next, html, web worker examples (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinpagtakhan authored Apr 28, 2022
1 parent e6f05a5 commit 81a8e86
Show file tree
Hide file tree
Showing 56 changed files with 17,973 additions and 0 deletions.
1 change: 1 addition & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
**/*.js
examples/
15 changes: 15 additions & 0 deletions examples/browser/chrome-ext/amplitude-min.js

Large diffs are not rendered by default.

45 changes: 45 additions & 0 deletions examples/browser/chrome-ext/background.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/**
* Amplitude using importScripts(). Create a copy of amplitude-min.js as part of your project and use the file path.
*/
importScripts('/amplitude-min.js');

/**
* Start by calling amplitude.init(). This must be done before any event tracking
* preferrably in the root file of the project.
*
* Calling init() requires an API key
* ```
* amplitude.init(API_KEY)
* ```
*
* Optionally, a user id can be provided when calling init()
* ```
* amplitude.init(API_KEY, '[email protected]')
* ```
*
* Optionally, a config object can be provided. Refer to https://amplitude.github.io/Amplitude-TypeScript/interfaces/Types.BrowserConfig.html
* for object properties.
*/
amplitude.init('API_KEY', '[email protected]');

chrome.omnibox.onInputEntered.addListener((text) => {
amplitude.track('Input Entered', { value: text });
var newURL = 'https://www.google.com/search?q=' + encodeURIComponent(text);
chrome.tabs.update({ url: newURL });
});

chrome.omnibox.onDeleteSuggestion.addListener((text) => {
amplitude.track('Delete Suggestion', { value: text });
});

chrome.omnibox.onInputCancelled.addListener((text) => {
amplitude.track('Input Cancelled', { value: text });
});

chrome.omnibox.onInputChanged.addListener((text) => {
amplitude.track('Input Changed', { value: text });
});

chrome.omnibox.onInputStarted.addListener((text) => {
amplitude.track('Input Started', { value: text });
});
12 changes: 12 additions & 0 deletions examples/browser/chrome-ext/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "Google Search Tracker",
"description": "Type 'g' plus a search term into the Omnibox to seach in google.com",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"omnibox": {
"keyword": "g"
}
}
52 changes: 52 additions & 0 deletions examples/browser/html-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
</head>
<script>
/**
* Install Amplitude using script loader. Refer to: https://github.com/amplitude/Amplitude-TypeScript/tree/main/packages/analytics-browser#using-script-loader.
*/
!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[]};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{r.invoked=!0;var n=t.createElement("script");n.type="text/javascript",n.integrity="sha384-TeoEVjqxsQrwhskzwWGK6epJC7EkYjvl7k4gmwunKlRBkUK9nT01H4FL9z4VPMSm",n.crossOrigin="anonymous",n.async=!0,n.src="https://cdn.amplitude.com/libs/analytics-browser-0.3.1-min.js.gz",n.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Error: could not load SDK")};var s=t.getElementsByTagName("script")[0];function v(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}}s.parentNode.insertBefore(n,s);for(var o=function(){return this._q=[],this},i=["add","append","clearAll","prepend","set","setOnce","unset","preInsert","postInsert","remove","getUserProperties"],a=0;a<i.length;a++)v(o,i[a]);r.Identify=o;for(var u=function(){return this._q=[],this},c=["getEventProperties","setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties"],p=0;p<c.length;p++)v(u,c[p]);r.Revenue=u;var l=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport"],d=["init","add","remove","track","logEvent","identify","groupIdentify","setGroup","revenue"];function m(e){function t(t,r){e[t]=function(){var n={promise:new Promise((r=>{e._q.push({name:t,args:Array.prototype.slice.call(arguments,0),resolve:r})}))};if(r)return n}}for(var r=0;r<l.length;r++)t(l[r],!1);for(var n=0;n<d.length;n++)t(d[n],!0)}m(r),e.amplitude=r}}(window,document)}();
/**
* Start by calling amplitude.init(). This must be done before any event tracking
* preferrably in the root file of the project.
*
* Calling init() requires an API key
* ```
* amplitude.init(API_KEY)
* ```
*
* Optionally, a user id can be provided when calling init()
* ```
* amplitude.init(API_KEY, '[email protected]')
* ```
*
* Optionally, a config object can be provided. Refer to https://amplitude.github.io/Amplitude-TypeScript/interfaces/Types.BrowserConfig.html
* for object properties.
*/
amplitude.init('API_KEY', '[email protected]');
</script>
<body>
<h2>Amplitude Analytics Browser Example with HTML</h2>

<button onclick="amplitude.identify(new amplitude.Identify().set('role', 'engineer'))">
Identify
</button>

<button onclick="amplitude.setGroup('org', 'engineering')">
Group
</button>

<button onclick="amplitude.groupIdentify('org', 'engineering', new amplitude.Identify().set('technology', 'react.js'))">
Group Identify
</button>

<button onclick="amplitude.track('Button Click', { name: 'HTML' })">
Track
</button>
</body>
</html>
3 changes: 3 additions & 0 deletions examples/browser/next-app/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
35 changes: 35 additions & 0 deletions examples/browser/next-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
34 changes: 34 additions & 0 deletions examples/browser/next-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `pages/index.tsx`. The page auto-updates as you edit the file.

[API routes](https://nextjs.org/docs/api-routes/introduction) can be accessed on [http://localhost:3000/api/hello](http://localhost:3000/api/hello). This endpoint can be edited in `pages/api/hello.ts`.

The `pages/api` directory is mapped to `/api/*`. Files in this directory are treated as [API routes](https://nextjs.org/docs/api-routes/introduction) instead of React pages.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
5 changes: 5 additions & 0 deletions examples/browser/next-app/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
6 changes: 6 additions & 0 deletions examples/browser/next-app/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}

module.exports = nextConfig
25 changes: 25 additions & 0 deletions examples/browser/next-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "next-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@amplitude/analytics-browser": "^0.3.1",
"next": "12.1.5",
"react": "18.1.0",
"react-dom": "18.1.0"
},
"devDependencies": {
"@types/node": "17.0.29",
"@types/react": "18.0.8",
"@types/react-dom": "18.0.0",
"eslint": "8.14.0",
"eslint-config-next": "12.1.5",
"typescript": "4.6.3"
}
}
28 changes: 28 additions & 0 deletions examples/browser/next-app/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import '../styles/globals.css'
import type { AppProps } from 'next/app'
import * as amplitude from '@amplitude/analytics-browser';

/**
* Start by calling amplitude.init(). This must be done before any event tracking
* preferrably in the root file of the project.
*
* Calling init() requires an API key
* ```
* amplitude.init(API_KEY)
* ```
*
* Optionally, a user id can be provided when calling init()
* ```
* amplitude.init(API_KEY, '[email protected]')
* ```
*
* Optionally, a config object can be provided. Refer to https://amplitude.github.io/Amplitude-TypeScript/interfaces/Types.BrowserConfig.html
* for object properties.
*/
amplitude.init('API_KEY', '[email protected]')

function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}

export default MyApp
10 changes: 10 additions & 0 deletions examples/browser/next-app/pages/api/hello.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next';

type Data = {
name: string;
};

export default function handler(req: NextApiRequest, res: NextApiResponse<Data>) {
res.status(200).json({ name: 'John Doe' });
}
41 changes: 41 additions & 0 deletions examples/browser/next-app/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { identify, setGroup, groupIdentify, track, Identify } from '@amplitude/analytics-browser'

const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>

<main className={styles.main}>
<h1 className={styles.title}>
Amplitude Analytics Browser Example with React
</h1>

<button onClick={() => identify(new Identify().set('role', 'engineer'))}>
Identify
</button>

<button onClick={() => setGroup('org', 'engineering')}>
Group
</button>

<button onClick={() => groupIdentify('org', 'engineering', new Identify().set('technology', 'react.js'))}>
Group Identify
</button>

<button onClick={() => track('Button Click', { name: 'App' })}>
Track
</button>
</main>
</div>
)
}

export default Home
Binary file added examples/browser/next-app/public/favicon.ico
Binary file not shown.
4 changes: 4 additions & 0 deletions examples/browser/next-app/public/vercel.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 81a8e86

Please sign in to comment.