在Google Analytics事件跟踪代码中使用Javascript来自动化类别命名

前端之家收集整理的这篇文章主要介绍了在Google Analytics事件跟踪代码中使用Javascript来自动化类别命名前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

所以我试图在动态生成页面上实现一些谷歌分析事件跟踪.我会用类似的东西

我想知道是否可以使用像document.title这样的东西从页面的html标题自动生成GA代码的类别部分?所有页面都使用独特的标题,如果在这些页面上跟踪的事件可以作为单独的条目而不仅仅是类别显示在GA中,那将会很棒.

最佳答案
这比我预想的要困难.希望能帮助到你.

Live demo with examples

JavaScript的

  1. // Unbind default behavIoUr
  2. $(document).off("ready.ga").on("ready",function () {
  3. //hollow out
  4. pageLoc = $(location).attr('href');
  5. // Introduce helper functions.
  6. (function ($,window,undef) {
  7. // ga selector.
  8. $.extend($.expr[":"],{
  9. ga: function (a) {
  10. var attr = a.attributes,len = attr.length;
  11. while (len--) {
  12. if (attr[len].name.indexOf("data-ga-") !== -1) {
  13. return true;
  14. }
  15. }
  16. return false;
  17. }
  18. });
  19. $.gaaApi = {
  20. trackEvent: {
  21. event: {
  22. value: "_trackEvent",validation: "isString",type: "string"
  23. },category: {
  24. value: null,validation: "optString",type: "currentloc"
  25. },action: {
  26. value: null,label: {
  27. value: null,value: {
  28. value: null,validation: "optInt",type: "integer"
  29. },nonInteraction: {
  30. value: null,validation: "optBool",type: "boolean"
  31. }
  32. },trackPageview: {
  33. event: {
  34. value: ["trackPageview",$(location).attr('href')],url: {
  35. value: undef,type: "string"
  36. }
  37. }
  38. };
  39. var validation = {
  40. isString: function (obj) {
  41. var empty = true;
  42. if (obj && typeof obj === "string") {
  43. empty = /^\s*$/.test(obj);
  44. }
  45. // If empty === true then something is wrong and we should return false.
  46. return !(empty);
  47. },optString: function (obj) {
  48. if (obj === undef) {
  49. return true;
  50. }
  51. return validation.isString(obj);
  52. },isInt: function (obj) {
  53. return (/^[\-+]?\d+$/).test(obj) || (obj === +obj && obj === (obj | 0));
  54. },optInt: function (obj) {
  55. if (obj === undef) {
  56. return true;
  57. }
  58. return validation.isInt(obj);
  59. },isFloat: function (obj) {
  60. return (/^[\-+]?\d+(\.\d+)?$/).test(obj) || (obj === +obj && obj !== (obj | 0));
  61. },optFloat: function (obj) {
  62. if (obj === undef) {
  63. return true;
  64. }
  65. return validation.isFloat(obj);
  66. },isBool: function (obj) {
  67. return (obj === true || obj === "true") || (obj === false || obj === "false");
  68. },optBool: function (obj) {
  69. if (obj === undef) {
  70. return true;
  71. }
  72. return validation.isBool(obj);
  73. }
  74. },methods = {
  75. validate: function (param,name,location) {
  76. var $element = this.$element,data = $element.data("ga-" + name.toLowerCase()),isValid;
  77. //pageLoc = $(location).attr('href');
  78. if (!validation[param.validation]) {
  79. throw new TypeError("Unknown validation type");
  80. }
  81. // Check the value.
  82. isValid = validation[param.validation](data);
  83. if (!isValid) {
  84. throw new Error("object validation error on " + name);
  85. }
  86. // Assign the value.
  87. // Some analytics methods accept numbers as strings so we check the return type.
  88. switch (param.type) {
  89. case "integer":
  90. return data ? parseInt(data,10) : null;
  91. case "float":
  92. return data ? parseFloat(data) : null;
  93. case "boolean":
  94. return data ? Boolean(data) : null;
  95. case "currentloc":
  96. return data;
  97. default:
  98. // Default to string.
  99. return data ? data + "" : null;
  100. }
  101. },createArgs: function () {
  102. var binder = this,event = this.event,args = $.map(event,function (val,key,pageLoc) {
  103. var pageLoc = $(location).attr('href');
  104. var value;
  105. if (key === "event") {
  106. // We don't want to check for the event property in the DOM.
  107. value = val.value;
  108. } else {
  109. // Validate and return the correct value from the DOM.
  110. value = methods.validate.call(binder,val,pageLoc);
  111. }
  112. return value;
  113. });
  114. return args;
  115. }
  116. },gaa = function (element,options) {
  117. this.$element = $(element);
  118. this.options = $.extend({},$.fn.gaa.defaults,options);
  119. };
  120. gaa.prototype = {
  121. constructor: gaa,trackEvent: function () {
  122. var trackedEvent = $.Event("tracked.ga");
  123. var currentLoc = $(location).attr('href');
  124. this.args = methods.createArgs.call(this);
  125. if (this.options.logit) {
  126. if (window.console && window.console.log) {
  127. // Push the data.
  128. console.log("pushing to Google analytics",this.args);
  129. this.$element.trigger(trackedEvent).trigger(currentLoc);
  130. // this.$element.trigger(currentLocation);
  131. }
  132. } else {
  133. var gaq = window._gaq;
  134. if (gaq) {
  135. // Set the context for our deferred callback.
  136. var binder = this;
  137. // Push the data.
  138. $.when(gaq.push(args)).done(
  139. function () {
  140. this.$element.trigger(trackedEvent);
  141. // this.$element.trigger(trackedEvent);
  142. // Redirect the location - delayed so that any other page functionality has time to run.
  143. setTimeout(function () {
  144. var href = binder.attr("href");
  145. if (href && href.indexOf("#") !== 0) {
  146. window.location = href;
  147. }
  148. },100);
  149. });
  150. } else {
  151. throw new ReferenceError(" _gaq not there");
  152. }
  153. }
  154. }
  155. };
  156. // wrapper definition
  157. $.fn.gaa = function (options) {
  158. return this.each(function () {
  159. var $this = $(this),data = $this.data("ga"),opts = typeof options === "object" ? options : null;
  160. if (!data) {
  161. // Check the data and assign if not present.
  162. $this.data("ga",(data = new gaa(this,opts)));
  163. }
  164. // Run the appropriate function is a string is passed.
  165. if (typeof options === "string") {
  166. data[options]();
  167. } else {
  168. var handler = data.options.handler.toLowerCase(),// Check for the event attr here as it might be other than the default.
  169. event = data.$element.attr("data-ga-event");
  170. // Overwrite if necessary.
  171. $.extend(data.options,{
  172. event: event
  173. });
  174. // Build the data as we have nothing there.
  175. // First assign the event.
  176. data.event = $.gaaApi[data.options.event];
  177. // Then bind the handler.
  178. if (handler === "load") {
  179. data.trackEvent();
  180. } else {
  181. data.$element.on(handler + ".ga",function (e) {
  182. e.preventDefault();
  183. data.trackEvent();
  184. });
  185. }
  186. }
  187. });
  188. };
  189. // Define the defaults.
  190. $.fn.gaa.defaults = {
  191. event: ["trackEvent","giveLocation"],handler: "load",logit: false
  192. };
  193. // Set the public constructor.
  194. $.fn.gaa.Constructor = gaa;
  195. // Let's BEGIN
  196. $(document).on("ready.ga",function () {
  197. // Bind using the custom selector.
  198. $(":ga").each(function () {
  199. $(this).gaa();
  200. });
  201. });
  202. }(jQuery,window));
  203. // Set some options the ones below are the defaults.
  204. var options = {
  205. event: "trackEvent",// The event name unprefixed.
  206. handler: "click",// The eventhandler to trigger the tracking.
  207. // Using 'load' will track immediately.
  208. logit: true,//to logit
  209. };
  210. var options2 = {
  211. event: "trackPageview",//to logit
  212. };
  213. var options3 = {
  214. event: "trackPageview",// The event name unprefixed.
  215. handler: "load",// The eventhandler to trigger the tracking.
  216. // Using 'load' will track immediately.
  217. logit: true //to logit
  218. };
  219. // Binds using the custom selector.
  220. $("load.trigger").gaa(options3); //fires a ga onload after domready
  221. $("button.button1").gaa(options2).click(function () {
  222. console.log('\nmore button events\n','heres the URL:',location.href)
  223. });
  224. $("#clickme").gaa(options).click(function () {
  225. $(this).toggleClass("changeIt");
  226. });
  227. });

的index.html

位置绑定发生在这里,让jquery正确地使用位置.

  1. event: {
  2. value: ["trackPageview",type: "string"
  3. }

你使用它的方法是正确的,但你必须提前获得位置才能进入ga.似乎无论如何这种格式

  1. $("#button").gaa(options).click(function () {
  2. $(this).toggleClass("changeIt");
  3. });

会让你朝着正确的方向前进.

这是一个有趣的脑袋.这应该可以让您访问location.href,稍后您需要它.想法是在DOM准备好之后但在_gaq执行之前形成绑定.

猜你在找的jQuery相关文章