我正在按照以下说明尝试通过JavaScript获取Google Optimize实验数据。但是我没有回调,也看不到调试器中发生的任何事情。
链接的说明使用了配置Google Analytics(分析)的gtag方式,因此我已经根据https://developers.google.com/gtagjs/devguide/snippet设置了gtag ,并根据https://support.google.com/配置了Optimize 使用方法1 优化/ answer / 7513085?hl = zh-CN :使用全局站点标签(gtag.js)安装优化。
我想显示我正在使用的确切代码,但是由于我是在React与Next.js服务器端渲染中进行的,因此与纯HTML + JS相比,原始代码有一些额外的东西。来源看起来像这样:
require("dotenv").config()
import React from "react"
import Document, { Head, Main, NextScript } from "next/document"
export default class extends Document {
render() {
return (
<html>
<Head>
<script async src={`https://www.googletagmanager.com/gtag/js?id=${process.env.GA_TRACKING_ID}`}/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){ dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', '${process.env.GA_TRACKING_ID}', { optimize_id: '${process.env.OPTIMIZE_ID}'});
console.log('GA setup done: ${process.env.GA_TRACKING_ID} + ${process.env.OPTIMIZE_ID}');
gtag('event', 'optimize.callback', {
name: '${process.env.EXPERIMENT_ID}',
callback: o => console.log(o)
});
`
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
)
}
}
This code produces a result page that starts Analytics and tracks a pageView just like it should, and when I do "RUN DIAGNOSTICS" in the Google Optimize console it opens the page, checks the JavaScript and reports:
Optimize is correctly installed
No major issues were detected while verifying the Optimize installation on this page.
I have also installed the Google Chrome Tag Assistant plug-in, and it reports that the Google Optimize tag is correctly installed.
I can see the following calls in the network log:
https://www.googletagmanager.com/gtag/js?id=UA-xxxxxx
https://www.google-analytics.com/analytics.js
https://www.google-analytics.com/gtm/js?id=GTM-xxxxxx&t=gtag_UA_xxxx&cid=nnn.nnn
I have also verified that the google_optimize
global variable is created, and it has a .get()
method. If I look (in the debugger network panel) at the http response of the https://www.google-analytics.com/gtm/js?...
request I can actually see the Google Optimize experiments data with the correct Experiment embedded in the code.
因此,一切看起来都不错,除了该optimize.callback
活动似乎是一场彻底的无人打扰。它什么也不做。而且我不知道如何通过其他方式访问调试器的http响应中看到的实验数据。
因此,我终于弄清楚了导致我挣扎的原因:我是从本地NodeJS服务器运行的,通常使用
http://localhost:3000
url。事实证明,Google Optimize 绝不会触发对http://localhost/...
网址的实验。该代码需要hostname
一部分URL,可以根据host.domain
方案进行解析。换句话说,主机名中必须有一个点,Optimize才能触发实验。
对于本地测试,可以通过创建主机名别名(例如
localhost.domain
for127.0.0.1
)并使用该别名访问网页来解决此问题。