Javascript 单击表单提交后在谷歌分析中跟踪事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4086587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Track event in google analytics upon clicking form submit
提问by at.
I need to track an event in google analytics when someone fills out a form and clicks submit. The resulting page that comes up is a standard dashboard-type page, so in order to track the event on that page I'd have to pass in the event in the url and then read the url and output the google analytics event tracking javascript code based on it. This is a frequently bookmarked page though and page that is reloaded, clicked back to, etc. So I'd really rather not pass tracking events in the URL and screw up the analytics.
当有人填写表单并点击提交时,我需要在谷歌分析中跟踪一个事件。出现的结果页面是一个标准的仪表板类型页面,因此为了跟踪该页面上的事件,我必须在 url 中传递事件,然后读取 url 并输出谷歌分析事件跟踪 javascript 代码基于它。这是一个经常添加书签的页面,并且页面会重新加载、点击返回等。所以我真的不想在 URL 中传递跟踪事件并搞砸分析。
Instead, I'd much rather do something like the following jQuery code on the page with the form:
相反,我更愿意使用表单在页面上执行类似以下 jQuery 代码的操作:
$('#form_id').submit(function() {
_gaq.push('_trackEvent', 'my category', 'my action');
});
The problem I fear with the above is that I'm going to miss some events being tracked because immediately after calling that javascript the browser is going to submit the form and go to another webpage. If the utm.gif tracking image isn't loaded in time, I miss the event :(.
我担心上面的问题是我会错过一些正在跟踪的事件,因为在调用该 javascript 之后,浏览器将立即提交表单并转到另一个网页。如果 utm.gif 跟踪图像没有及时加载,我会错过这个事件:(。
Is my fear justified? How do I ensure I don't miss events being tracked?
我的恐惧有道理吗?如何确保我不会错过正在跟踪的事件?
采纳答案by Yahel
There are only 2 ways to ensure, 100%, that all form submissions (amongst users who have JS enabled and who don't block GA) is as follows:
只有两种方法可以 100% 确保所有表单提交(在启用 JS 且未阻止 GA 的用户中)如下:
- You can do an AJAX submit, and then not have to worry about the page changing, and thus have all the time in the world for GA to process AND your new page to load in place of the old one.
- You can force the form to open its action in a new window, thus leaving all background processes on the main page working, and preventing the race condition you're worried about.
- 您可以执行 AJAX 提交,然后不必担心页面更改,从而有时间让 GA 处理并加载新页面以代替旧页面。
- 您可以强制表单在新窗口中打开其操作,从而使主页上的所有后台进程保持工作状态,并防止出现您担心的竞争情况。
The reason for this is that Google Analytics does not have a callback function, so you can't ever be certain you're capturing allof the submits, even if you put a 10 second lag.
这样做的原因是 Google Analytics 没有回调函数,因此您永远无法确定是否捕获了所有提交,即使您设置了 10 秒的延迟。
Alternately, you can just pass a GET value to the submitted page and setup a check on that page for the value. If its set, you can send a trackEvent call.
或者,您可以将 GET 值传递给提交的页面并在该页面上设置该值的检查。如果设置,您可以发送 trackEvent 调用。
回答by flu
Use Google Analytics hitCallback
使用谷歌分析hitCallback
You can specify a custom callback function on the tracker object.
您可以在跟踪器对象上指定自定义回调函数。
_gaq.push(['_set', 'hitCallback', function(){}]);
The callback is invoked after the "hit is sent successfully."
在“命中发送成功”后调用回调。
If you want to track a click on a submit button and send the form afterwards you can use the following code (uses jQuery) for your event:
如果您想跟踪提交按钮上的点击并在之后发送表单,您可以为您的事件使用以下代码(使用 jQuery):
var _this = this; // The form input element that was just clicked
_gaq.push(['_set','hitCallback',function() {
$(_this).parents('form').first().submit(); // Submit underlying form
}]);
_gaq.push(['_trackEvent', 'My category', 'My action']);
return !window._gat; // Ensure that the event is bubbled if GA is not loaded
Or as onclick
one liner for your <input type="submit">
element:
或者作为onclick
您<input type="submit">
元素的一个衬垫:
onclick="var _this=this;_gaq.push(['_set','hitCallback',function(){$(_this).parents('form').first().submit();}]);_gaq.push(['_trackEvent','My category','My action']);return !window._gat;"
What it does it that it tracks the event My category/My action
, uses jQuery to find the underlying form element of the submit button just pushed, and then submits the whole form.
它做了什么,它跟踪事件My category/My action
,使用 jQuery 查找刚刚按下的提交按钮的底层表单元素,然后提交整个表单。
See: Google Analytics - Sending Data to Google Analytics - Hit Callback(thanks supervacuo)
请参阅:Google Analytics - 将数据发送到 Google Analytics - 点击回调(感谢 supervacuo)
UPDATEIf you're using modern analytics.js code with ga() function defined, you can write this as following:
更新如果你使用定义了 ga() 函数的现代 analytics.js 代码,你可以这样写:
var _this = this;
ga('send', 'event', 'My category', 'My action', {
'hitCallback': function() {
$(_this).parents('form').first().submit();
}
});
return !window.ga;
回答by Dmytro Pastovenskyi
For those who deal with google analytics universal and doing some trick with hitCallback (f.x. track event after validation but before submit of form) keep in mind that google-analytics.js potentially could be blocked, however ga function will be still defined, so submit will not happen.
对于那些处理通用 google 分析并使用 hitCallback(验证后但提交表单前的 fx 跟踪事件)的人,请记住 google-analytics.js 可能会被阻止,但仍会定义 ga 函数,因此请提交不会发生。
ga('send', 'pageview', event, {
'hitCallback': function() {
_this.submit();
}
})
return !window.ga;
Can be fixed with validation that check if ga is loaded
可以通过检查 ga 是否加载的验证来修复
ga('send', 'pageview', event, {
'hitCallback': function() {
_this.submit();
}
})
return !(ga.hasOwnProperty('loaded') && ga.loaded === true)
回答by epocsquadron
This question is a few years old now, and it seems that google analytics has provided a way to do this without the hacks given above.
这个问题已经有几年了,似乎谷歌分析已经提供了一种无需上述黑客攻击的方法。
From the google analytics docs:
来自谷歌分析文档:
In addition to command arrays, you can also push function objects onto the _gaq queue. The functions can contain any arbitrary JavaScript and like command arrays, they are executed in the order in which they are pushed onto _gaq.
除了命令数组,您还可以将函数对象推送到 _gaq 队列。这些函数可以包含任意的 JavaScript 和命令数组,它们按照被推送到 _gaq 的顺序执行。
You can combine this with multiple-command pushing to make aboslute sure that they are added in order (and save a call).
您可以将其与多命令推送结合起来,以确保它们按顺序添加(并保存调用)。
$('input[type="submit"]').click(function(e) {
// Prevent the form being submitted just yet
e.preventDefault();
// Keep a reference to this dom element for the callback
var _this = this;
_gaq.push(
// Queue the tracking event
['_trackEvent', 'Your event', 'Your action'],
// Queue the callback function immediately after.
// This will execute in order.
function() {
// Submit the parent form
$(_this).parents('form').submit();
}
);
});
回答by jsalvata
WHile the hitCallback solution is good, I prefer setting a cookie and triggering the event from the next page. In this way a failure in GA won't stop my site:
虽然 hitCallback 解决方案很好,但我更喜欢设置 cookie 并从下一页触发事件。这样,GA 中的失败不会停止我的网站:
// Function to set the event to be tracked:
function setDelayedEvent(category, action, label, value) {
document.cookie='ev='+escape(category)+'!'+escape(action)+'!'+escape(label)+'!'+value
+'; path=/; expires='+new Date(new Date().getTime()+60000).toUTCString();
}
// Code run in every page, in case the previous page left an event to be tracked:
var formErrorCount= formErrorCount || 0;
var ev= document.cookie.match('(?:;\s*|^)ev=([^!]*)!([^!]*)!([^!]+)!([^!]+)(?:;|\s*$)');
if (ev && ev.length>2) {
_gaq.push(['_trackEvent', unescape(ev[1]), unescape(ev[2]),
unescape(ev[3]), parseInt(ev[4])]);
document.cookie='ev=; path=/; expires='+new Date(new Date().getTime()-1000).toUTCString();
}
回答by lonesomeday
If you aren't too bothered about 100% accuracy, you could just stick a 1-second delay in.
如果您不太担心 100% 的准确度,您可以延迟 1 秒。
$('#form_id').submit(function(e) {
var form = this;
e.preventDefault(); // disable the default submit action
_gaq.push('_trackEvent', 'my category', 'my action');
$(':input', this).attr('disabled', true); // disable all elements in the form, to avoid multiple clicks
setTimeout(function() { // after 1 second, submit the form
form.submit();
}, 1000);
});
回答by Tom S?derlund
This is how you do event callbacks in gtag.js
, to ensure Google Analytics data is sent before you change the page URL:
这是您在 中执行事件回调的方式gtag.js
,以确保在更改页面 URL 之前发送 Google Analytics 数据:
gtag('event', 'view_promotion', { myParameter: myValue, event_callback: function () {
console.log('Done!');
// Now submit form or change location.href
} });
Source: https://developers.google.com/analytics/devguides/collection/gtagjs/sending-hits
来源:https: //developers.google.com/analytics/devguides/collection/gtagjs/sending-hits
回答by Tushar
Okay since we have moved to Universal analytics, I would like to answer the same using GTM and UA.
好的,既然我们已经转向通用分析,我想使用 GTM 和 UA 回答同样的问题。
GTM:
GTM:
Track event in google analytics upon clicking form submit is fairly easy using GTM.
使用 GTM 在点击表单提交时在谷歌分析中跟踪事件相当容易。
- Create a UA tag and set the type to
event
in GTM. - Fill your desired Event Action, Category and Label
- Create the trigger of type Form Submission.
- Put more conditions to target the button you desire
- 创建 UA 标签并将类型设置为
event
in GTM。 - 填写您想要的事件操作、类别和标签
- 创建表单提交类型的触发器。
- 设置更多条件来定位您想要的按钮
This is the best, optimal and easy going approach for the OP.
这是 OP 的最佳、最佳且易于使用的方法。
回答by Alexander Filatov
When it's crucial that every submit is tracked, I usually set a cookie on the backend with all required data. Then set up a rule in GTM to fire off a tag based on existence of this 1st party cookie. The tag parses the cookie for required values and does whatever is required with them and remove the cookie.
当跟踪每个提交至关重要时,我通常在后端设置一个包含所有必需数据的 cookie。然后在 GTM 中设置规则以根据此第一方 cookie 的存在触发标签。该标签解析 cookie 以获得所需的值,并对其执行所需的任何操作并删除 cookie。
A more complex example is purchase tracking. You want to fire off 5 different tags when user performs a purchase. Race conditions and the immediate redirect to some welcome page make it difficult to rely on simple "onSubmit" tracking. So I set a cookie with all purchase-related data and on whatever page the user ends up on GTM will recognize the cookie, fire off an "entry point" tag which will parse the cookie, push all values to dataLayer, remove the cookie and then the tag itself will push events to dataLayer thereby triggering the 5 tags that require the purchase data (which is already in dataLayer).
一个更复杂的例子是购买跟踪。您希望在用户执行购买时触发 5 个不同的标签。竞争条件和立即重定向到某个欢迎页面使得依赖简单的“onSubmit”跟踪变得困难。所以我设置了一个包含所有购买相关数据的 cookie 并且在用户最终在 GTM 上的任何页面上都会识别 cookie,触发一个“入口点”标签,该标签将解析 cookie,将所有值推送到 dataLayer,删除 cookie 并然后标签本身会将事件推送到 dataLayer,从而触发需要购买数据(已经在 dataLayer 中)的 5 个标签。