Google 分析 v3(通用分析)
此库输出 @analytics/google-analytics-v3 该插件 analytics 用于任何工程的软件包独立方法( i) 谷歌分析。 。 。 .
此分析插件会将 google 分析器装入您的应用程序 .
详情 见文件。 。 。 .
升级到谷歌分析 v4
说明: GA3将于2023年7月开始贬值. 你可能想改用谷歌分析4.
关于最新版本的谷歌分析,请参见 @analytics/google-analytics 软件包 或 GA4 插件文件
单击以扩展
安装
npm install analytics
npm install @analytics/google-analytics-v3
如何使用
这个 @analytics/google-analytics-v3 软件包在 浏览器 财务报告和审定财务报表 在节点.js的服务器侧。要使用、安装软件包,在您的工程中包含并初始化插件 分析。 。 。 .
以下为如何使用浏览器插件的例子.
import Analytics from 'analytics'
import googleAnalyticsV3 from '@analytics/google-analytics-v3'
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalyticsV3({
trackingId: 'UA-1234567'
})
]
})
/* Track a page view */
analytics.page()
/* Track a custom event */
analytics.track('playedVideo', {
category: 'Videos',
label: 'Fall Campaign',
value: 42
})
/* Identify a visitor */
analytics.identify('user-id-xyz', {
firstName: 'bill',
lastName: 'murray'
})
初始化后 analytics 与 googleAnalyticsV3 插件, 数据将发送到 Google 分析器 分析. p, (中文(简体) ), 分析. track,或 分析 识别 被调用.
见 其他执行实例 在您的项目中使用更多细节 .
支持的平台
这个 @analytics/google-analytics-v3 软件包在 浏览器 财务报告和审定财务报表 在节点.js的服务器侧
浏览器使用量
Google Analytics客户端浏览器插件使用这些分析的api方法:
浏览器 API
import Analytics from 'analytics'
import googleAnalyticsV3 from '@analytics/google-analytics-v3'
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalyticsV3({
trackingId: 'UA-1234567'
})
]
})
浏览器配置选项
| 选项 | 说明 |
|---|---|
trackingId 所需经费 - 绳子 | 谷歌分析网站跟踪 Id |
debug 选项 - 布尔 | 启用 Google 分析调试模式 |
anonymizeIp 选项 - 布尔 | 启用 IP地址匿名化 发送到谷歌分析. 详见下文 |
customDimensions 选项 - 对象 | 地图 自定义尺寸 将额外信息发送给谷歌分析. 详见下文 |
resetCustomDimensionsOnPage 选项 - 对象 | 在分析器上按键重置自定义维度. page () calls. 用于单页应用程序 . |
setCustomDimensionsToPage 选项 - 布尔 | Mapped 维度将被设置到页面中, 作为该页面中所有后续事件的属性发送 。 如果错误, 分析将只作为单个事件的一部分通过自定义维度 |
instanceName 选项 - 绳子 | 自定义 google 分析器的跟踪器名称 。 如果您需要装入多个google分析脚本, 请使用此功能 |
customScriptSrc 选项 - 绳子 | 如果代理调用, 自定义谷歌分析脚本的 URL |
cookieConfig 选项 - 对象 | 配置时的额外 cookie 属性 饼干 |
tasks 选项 - 对象 | 设定自定义 google 分析任务 |
nonce 选项 - 绳子 | 内容-安全政策非现金价值 |
服务器侧用法
Google Analytics 服务器端节点. js 插件与这些分析的 api 方法一起工作:
服务器侧 API
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalytics({
trackingId: '123-xyz'
})
]
})
服务器侧配置选项
| 选项 | 说明 |
|---|---|
trackingId 所需经费 - 绳子 | 谷歌分析网站跟踪 Id |
其他例子
以下是其他执行实例.
服务器侧 ES6
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalytics({
trackingId: '123-xyz'
})
// ...other plugins
]
})
/* Track a page view */
analytics.page()
/* Track a custom event */
analytics.track('cartCheckout', {
item: 'pink socks',
price: 20
})
/* Identify a visitor */
analytics.identify('user-id-xyz', {
firstName: 'bill',
lastName: 'murray'
})
具有共同JS的服务器端节点.js
如果使用节点,您将想要导入 .default
const analyticsLib = require('analytics').default
const googleAnalytics = require('@analytics/google-analytics-v3').default
const analytics = analyticsLib({
app: 'my-app-name',
plugins: [
googleAnalytics({
trackingId: '123-xyz'
})
]
})
/* Track a page view */
analytics.page()
/* Track a custom event */
analytics.track('cartCheckout', {
item: 'pink socks',
price: 20
})
/* Identify a visitor */
analytics.identify('user-id-xyz', {
firstName: 'bill',
lastName: 'murray'
})
在 HTML 中使用
以下是通过unpkg CDN导入的例子. 请注意,这将拉入该套件的最新版本.
<!DOCTYPE html>
<html>
<head>
<title>Using @analytics/google-analytics-v3 in HTML</title>
<script src="https://unpkg.com/analytics/dist/analytics.min.js"></script>
<script src="https://unpkg.com/@analytics/google-analytics-v3/dist/@analytics/google-analytics-v3.min.js"></script>
<script type="text/javascript">
/* Initialize analytics */
var Analytics = _analytics.init({
app: 'my-app-name',
plugins: [
analyticsGa.init({
trackingId: 'UA-1234567'
})
]
})
/* Track a page view */
analytics.page()
/* Track a custom event */
analytics.track('playedVideo', {
category: 'Videos',
label: 'Fall Campaign',
value: 42
})
/* Identify a visitor */
analytics.identify('user-id-xyz', {
firstName: 'bill',
lastName: 'murray'
})
</script>
</head>
<body>
....
</body>
</html>
通过 ES 模块在 HTML 中使用
使用 @analytics/google-analytics-v3 在无害环境管理模块中.
<!DOCTYPE html>
<html>
<head>
<title>Using @analytics/google-analytics-v3 in HTML via ESModules</title>
<script>
// Polyfill process.
// **Note**: Because `import`s are hoisted, we need a separate, prior <script> block.
window.process = window.process || { env: { NODE_ENV: 'production' } }
</script>
<script type="module">
import analytics from 'https://unpkg.com/analytics/lib/analytics.browser.es.js?module'
import analyticsGa from 'https://unpkg.com/@analytics/google-analytics-v3/lib/analytics-plugin-ga.browser.es.js?module'
/* Initialize analytics */
const Analytics = analytics({
app: 'analytics-html-demo',
debug: true,
plugins: [
analyticsGa({
trackingId: 'UA-1234567'
})
// ... add any other third party analytics plugins
]
})
/* Track a page view */
analytics.page()
/* Track a custom event */
analytics.track('playedVideo', {
category: 'Videos',
label: 'Fall Campaign',
value: 42
})
/* Identify a visitor */
analytics.identify('user-id-xyz', {
firstName: 'bill',
lastName: 'murray'
})
</script>
</head>
<body>
....
</body>
</html>
匿名访问IP
谷歌分析允许您使用 匿名访问者IP地址。 。 。 .
要匿名 您的访客的IP地址设置 anonymizeIp 配置选项.
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
/* initialize analytics */
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalytics({
trackingId: 'UA-1223141231',
/* Anonymize the IP addresses */
anonymizeIp: true
}),
]
})
定制事件有效载荷
将跟踪自定义事件发送到 Google 分析器 eventLabel, (中文(简体) ), eventCategory,以及 eventValue 字段中,添加 label, (中文(简体) ), category,以及 value 事件属性的密钥.
analytics.track('play', {
category: 'Videos',
label: 'Fall Campaign',
value: 42
})
使用 GA 自定义尺寸
用于 Google 分析自定义尺寸,使用 customDimensions 配置选项和将值映射到自定义维度槽.
设置“ 海关地址” 选项
初始化时 analytics,确保设置 customDimensions 并绘制您的值 .
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
/* initialize analytics */
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalytics({
trackingId: 'UA-1223141231',
/* Map your Google Analytics custom dimensions here */
customDimensions: {
baz: 'dimension1',
foo: 'dimension2',
flam: 'dimension3',
},
}),
]
})
上面的配置将映射 巴兹 改为 dimension1, (中文(简体) ), o 改为 dimension2,以及 花点 改为 dimension3
何时 track, (中文(简体) ), page,或 identify 将自动设定到 Google 分析自定义维度.
/* Tracking example */
analytics.track('buttonClicked', {
baz: 'hello', // baz is mapped to GA custom dimension "dimension1"
foo: 'cool' // foo is mapped to GA custom dimension "dimension2"
})
在引擎盖下,分析器会自动设定Google Analytics中的自定义维度:
window.ga('set', {dimension1: 'hello', dimension2: 'cool'})
这也与页面识别调用相关( D) .
/* Identify example */
analytics.identify('user123', {
flam: 'wow' // flam is mapped to GA custom dimension "dimension3"
})
// This is mapped to window.ga('set', { dimension3: 'wow' })
使用多个实例
虽然没有建议,但有可能使用 多个谷歌分析实例 在一个网站.
在应用程序中使用不止一个google分析实例 instanceName 配置字段并确保覆盖默认插件 name。 。 。 .
以下是在应用中使用2个Google分析实例的例子.
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
// Normal google analytics instance
const instanceOne = googleAnalytics({
trackingId: '123-xyz',
})
// Second google analytics instance with override for 'name' field of the plugin
const instanceTwo = {
// initialize the 2nd instance with 'instanceName' field set
...googleAnalytics({
trackingId: '567-abc',
instanceName: 'two'
}),
// change 'name' plugin to avoid namespace collisions
...{
name: 'google-analytics-two'
}
}
/* Object.assign example
const instanceTwo = Object.assign({}, googleAnalytics({
trackingId: '567-abc',
instanceName: 'two'
}), {
name: 'google-analytics-two'
}
}) */
const analytics = Analytics({
app: 'awesome-app',
plugins: [
// Instance 1 of Google Analytics
instanceOne,
// Instance 2 of Google Analytics
instanceTwo
]
})
使用上述配置,所有跟踪,页面浏览和识别调用将流入Google Analytics的两个账户.
自定义代理端点
具体 假设,您可能想要加载您自己的版本的google分析器,以将请求发送给代理服务器.
要做到这一点,你可以添加 customScriptSrc 选项指向您的自定义 Google 分析脚本.
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalytics({
trackingId: '123-xyz',
customScriptSrc: 'https://my-url.com/to-custom-ga.js'
})
]
})
如果使用相近的终点,则建议将这一技术与 无轨 确保网站访问者隐私的插件 .
电子 Apps 浏览器扩展
Electron apps 捆绑并服务他们的代码从 file:// 扩展名。 同样,浏览器扩展服务文件来自 chrome-extension://由此引发的问题有: 这个 打开 这个 与谷歌分析.
要修复铬扩展,请使用 tasks 配置和设置 checkProtocolTask 改为 null。 。 。 .
为了修复电子应用程序,使用 tasks 配置选项如下并设定 checkProtocolTask, (中文(简体) ), checkStorageTask,并 historyImportTask 改为 null。 。 。 .
以下是一个例子:
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
/* initialize analytics and load plugins */
const analytics = Analytics({
app: 'my-app',
plugins: [
googleAnalytics({
trackingId: '123-xyz',
// Override or disable GA Tasks https://bit.ly/31Xetmg
tasks: {
// Set checkProtocolTask, checkStorageTask, & historyImportTask for electron apps
checkProtocolTask: null,
checkStorageTask: null,
historyImportTask: null,
}
}),
]
})
自定义 GA 任务
在特定情况下,您可能需要禁用或更改 默认 Google 分析任务。 。 。 .
例如,您可能想要取消请求或丰富请求。 你可以通过 分析插件 或使用 tasks 访问 GA 插件上的配置选项 tracker 仅限GA.
以下列出可连接到的任务( I) GA 任务文件
customTask默认情况下,此任务毫无作用 。 覆盖它以提供自定义行为.previewTask如果只为生成 Safari 的 “ Top Sites ” 缩略图, 则中止请求 .checkProtocolTask如果页面协议不是https或https,则中止请求.validationTask如果需要的字段缺失或无效,则中止请求.checkStorageTask如果跟踪器被配置到使用 cookie 时中止请求, 但用户的浏览器已禁用 cookie .historyImportTask从 ga.js/urchin.js 饼干中导入信息,以便在一个网站迁移到通用分析器时保存历史.samplerTask根据这个追踪器的样本Rate设置 给访客取出样本.buildHitTask构建测量协议请求字符串并存储在 hitPayload 字段.sendHitTask将存储在 hitPayload 字段的测量协议请求传递给谷歌分析服务器.timingTask基于此跟踪器的站点SpeedSampleRate设置,自动生成站点速度计时击出.displayFeaturesTask如果显示功能被启用, 则发送额外命中( 以前命中没有在广告功能 cookie ( Gat) 设定的超时时间内发送) .
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
/* initialize analytics and load plugins */
const analytics = Analytics({
app: 'cool-app',
plugins: [
googleAnalytics({
trackingId: '123-xyz',
// Override or disable GA Tasks https://bit.ly/31Xetmg
tasks: {
// https://developers.google.com/analytics/devguides/collection/analyticsjs/tasks#adding_to_a_task
sendHitTask: function (tracker) {
// Save original Task
var originalTask = tracker.get('sendHitTask')
// Modifies sendHitTask to send a copy of the request to a local server after
tracker.set('sendHitTask', function (model) {
// 1. Send the normal request to www.google-analytics.com/collect.
originalTask(model);
// 2. Send to local server
var xhr = new XMLHttpRequest();
xhr.open('POST', '/localhits', true);
xhr.send(model.get('hitPayload'));
})
},
// https://developers.google.com/analytics/devguides/collection/analyticsjs/tasks#aborting_task_processing
buildHitTask: (tracker) => {
// Save original Task
const originalBuildHitTask = tracker.get('buildHitTask')
// Set custom buildHitTask with abort
tracker.set('buildHitTask', function (model) {
if (document.cookie.match(/testing=true/)) {
throw new Error('Aborted tracking for test user.')
}
originalBuildHitTask(model);
})
},
}
}),
]
})
Cookie 配置
有些情况需要改变 饼干属性 谷歌分析饼干本身.
可用的GA Cookie字段为:
| 字段名称 | 数值类型 | 默认值 | 说明 |
|---|---|---|---|
cookieName | 文本 | 宽度( g) | 用于存储分析数据的饼干名称 |
cookieDomain | 文本 | 下列JavaScript表达式的结果: 文档. location.hostname | 指定用于存储分析饼干的域。 设为“ 无” 设置 cookie 不指定域 . |
cookieExpires | 整数 | 63072000 (中文(简体) ) (两年,以秒计) | 指定饼干过期, 秒. |
cookieUpdate | 布尔 | 真实 | 当 cookie Update 设定为真实(默认值)时, analytics.js 将在每页负载上更新 cookie. 这将更新相对于最近访问网站时设定的饼干过期时间 . |
cookieFlags | 文本 | 指定在 cookie 中附加的额外旗帜。 旗帜必须用分号分隔. |
您可以在 cookieConfig 在插件配置上.
import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics-v3'
const analytics = Analytics({
app: 'awesome-app',
plugins: [
googleAnalytics({
trackingId: 'UA-1234567',
cookieConfig: {
cookieName: 'gaCookie',
cookieDomain: 'blog.example.co.uk',
cookieExpires: 60 * 60 * 24 * 28, // Time in seconds.
cookieUpdate: 'false',
cookieFlags: 'SameSite=None; Secure',
}
})
]
})