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.
当有人填写表单并单击submit时,我需要在谷歌分析中跟踪事件。出现的结果页面是一个标准的指示板类型的页面,因此为了跟踪页面上的事件,我必须在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?
是我的担心有道理吗?如何确保不会错过被跟踪的事件?
9 个解决方案
#1
17
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.
- 您可以做一个AJAX提交,然后不必担心页面的更改,这样就有足够的时间让GA处理,新的页面可以代替旧的页面加载。
- 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.
- 您可以强制窗体在一个新窗口中打开它的动作,从而使主页面上的所有后台进程保持工作状态,并防止您担心的竞争状况。
The reason for this is that Google Analytics does not have a callback function, so you can't ever be certain you're capturing all of the submits, even if you put a 10 second lag.
原因是谷歌分析没有回调函数,所以你不能确定你捕获了所有提交,即使你延迟了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调用。
#2
143
Use Google Analytics 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:
如果您想跟踪单击submit按钮并随后发送表单,您可以使用以下代码(使用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:
或作为您的元素的onclickone线性:
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找到刚刚按下的submit按钮的底层表单元素,然后提交整个表单。
See: Google Analytics - Sending Data to Google Analytics - Hit Callback (thanks supervacuo)
参见:谷歌分析—将数据发送到谷歌分析—按回调(感谢super空)
UPDATE If you're using modern analytics.js code with ga() function defined, you can write this as following:
如果您正在使用现代分析,请进行更新。定义了ga()函数的js代码,可以这样写:
var _this = this;
ga('send', 'event', 'My category', 'My action', {
'hitCallback': function() {
$(_this).parents('form').first().submit();
}
});
return !window.ga;
#3
12
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.
对于使用谷歌analytics universal并使用hitCallback (f.x.在验证后但提交表单之前跟踪事件)的人,请记住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)
#4
7
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.
这个问题已经有好几年的历史了,看来谷歌analytics已经提供了一种方法来解决这个问题,而不需要上面提到的技巧。
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();
}
);
});
#5
6
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);
});
#6
6
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();
}
#7
2
This is how you do event callbacks in gtag.js
, to ensure Google Analytics data is sent before you change the page URL:
这就是如何在gtag中执行事件回调。为了确保谷歌分析数据在更改页面URL之前被发送:
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
#8
1
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. - 创建一个UA标签并将类型设置为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
- 为你想要的按钮添加更多的条件
This is the best, optimal and easy going approach for the OP.
对于OP来说,这是最好的、最优的、易于操作的方法。
#9
0
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中建立一个规则,根据第一个party 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将认识到饼干,发射一个“入口点”标签,将解析饼干,推动所有值dataLayer、删除cookie,然后标记本身将事件dataLayer从而引发5标签,需要购买数据(已经在dataLayer)。
#1
17
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.
- 您可以做一个AJAX提交,然后不必担心页面的更改,这样就有足够的时间让GA处理,新的页面可以代替旧的页面加载。
- 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.
- 您可以强制窗体在一个新窗口中打开它的动作,从而使主页面上的所有后台进程保持工作状态,并防止您担心的竞争状况。
The reason for this is that Google Analytics does not have a callback function, so you can't ever be certain you're capturing all of the submits, even if you put a 10 second lag.
原因是谷歌分析没有回调函数,所以你不能确定你捕获了所有提交,即使你延迟了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调用。
#2
143
Use Google Analytics 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:
如果您想跟踪单击submit按钮并随后发送表单,您可以使用以下代码(使用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:
或作为您的元素的onclickone线性:
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找到刚刚按下的submit按钮的底层表单元素,然后提交整个表单。
See: Google Analytics - Sending Data to Google Analytics - Hit Callback (thanks supervacuo)
参见:谷歌分析—将数据发送到谷歌分析—按回调(感谢super空)
UPDATE If you're using modern analytics.js code with ga() function defined, you can write this as following:
如果您正在使用现代分析,请进行更新。定义了ga()函数的js代码,可以这样写:
var _this = this;
ga('send', 'event', 'My category', 'My action', {
'hitCallback': function() {
$(_this).parents('form').first().submit();
}
});
return !window.ga;
#3
12
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.
对于使用谷歌analytics universal并使用hitCallback (f.x.在验证后但提交表单之前跟踪事件)的人,请记住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)
#4
7
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.
这个问题已经有好几年的历史了,看来谷歌analytics已经提供了一种方法来解决这个问题,而不需要上面提到的技巧。
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();
}
);
});
#5
6
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);
});
#6
6
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();
}
#7
2
This is how you do event callbacks in gtag.js
, to ensure Google Analytics data is sent before you change the page URL:
这就是如何在gtag中执行事件回调。为了确保谷歌分析数据在更改页面URL之前被发送:
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
#8
1
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. - 创建一个UA标签并将类型设置为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
- 为你想要的按钮添加更多的条件
This is the best, optimal and easy going approach for the OP.
对于OP来说,这是最好的、最优的、易于操作的方法。
#9
0
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中建立一个规则,根据第一个party 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将认识到饼干,发射一个“入口点”标签,将解析饼干,推动所有值dataLayer、删除cookie,然后标记本身将事件dataLayer从而引发5标签,需要购买数据(已经在dataLayer)。