2013-04-11 1 views
5

그래서 동적으로 생성 된 페이지에서 일부 Google Analytics 이벤트 추적을 구현하려고합니다. 내가 궁금하네요Google 애널리틱스 이벤트 추적 코드에서 자바 스크립트를 사용하여 카테고리 이름 지정 자동화

<script> 
$(document).ready(function(){ 
    $("#button1").click(function(){ 
    _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction)']); 
    }); 
    $("#button2").click(function(){ 
    _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction']); 
    }); 
}); 
</script> 

같은 것을 사용하게 될이 페이지의 HTML 제목에서 GA 코드의 범주 섹션을 생성 자동으로 document.title 같은 것을 사용하는 것이 가능하다? 모든 페이지는 고유 한 제목을 사용하며 해당 페이지에서 추적 된 이벤트가 카테고리가 아닌 별도의 항목으로 GA에 표시 될 수 있으면 좋을 것입니다.

답변

4

예상보다 힘들었습니다. 희망이 도움이됩니다.

Live demo with examples

자바 스크립트

// Unbind default behaviour 
    $(document).off("ready.ga").on("ready", function() { 
     //hollow out 
     pageLoc = $(location).attr('href'); 
     // Introduce helper functions. 

     (function ($, window, undef) { 
      // ga selector. 

      $.extend($.expr[":"], { 
       ga: function (a) { 
        var attr = a.attributes, 
         len = attr.length; 

        while (len--) { 
         if (attr[len].name.indexOf("data-ga-") !== -1) { 
          return true; 
         } 
        } 

        return false; 
       } 
      }); 

      $.gaaApi = { 
       trackEvent: { 
        event: { 
         value: "_trackEvent", 
         validation: "isString", 
         type: "string" 
        }, 
        category: { 
         value: null, 
         validation: "optString", 
         type: "currentloc" 
        }, 
        action: { 
         value: null, 
         validation: "optString", 
         type: "string" 
        }, 
        label: { 
         value: null, 
         validation: "optString", 
         type: "string" 
        }, 
        value: { 
         value: null, 
         validation: "optInt", 
         type: "integer" 
        }, 
        nonInteraction: { 
         value: null, 
         validation: "optBool", 
         type: "boolean" 
        } 
       }, 
       trackPageview: { 

        event: { 
         value: ["trackPageview", $(location).attr('href')], 
         validation: "isString", 
         type: "string" 
        }, 
        url: { 
         value: undef, 
         validation: "optString", 
         type: "string" 
        } 
       } 
      }; 

      var validation = { 

       isString: function (obj) { 

        var empty = true; 

        if (obj && typeof obj === "string") { 
         empty = /^\s*$/.test(obj); 
        } 
        // If empty === true then something is wrong and we should return false. 
        return !(empty); 

       }, 

       optString: function (obj) { 
        if (obj === undef) { 
         return true; 
        } 

        return validation.isString(obj); 
       }, 

       isInt: function (obj) { 
        return (/^[\-+]?\d+$/).test(obj) || (obj === +obj && obj === (obj | 0)); 
       }, 

       optInt: function (obj) { 

        if (obj === undef) { 
         return true; 
        } 

        return validation.isInt(obj); 
       }, 

       isFloat: function (obj) { 

        return (/^[\-+]?\d+(\.\d+)?$/).test(obj) || (obj === +obj && obj !== (obj | 0)); 
       }, 

       optFloat: function (obj) { 
        if (obj === undef) { 
         return true; 
        } 

        return validation.isFloat(obj); 
       }, 

       isBool: function (obj) { 
        return (obj === true || obj === "true") || (obj === false || obj === "false"); 

       }, 

       optBool: function (obj) { 

        if (obj === undef) { 
         return true; 
        } 

        return validation.isBool(obj); 
       } 
      }, 

      methods = { 

       validate: function (param, name, location) { 

        var $element = this.$element, 
         data = $element.data("ga-" + name.toLowerCase()), 
         isValid; 
        //pageLoc = $(location).attr('href'); 

        if (!validation[param.validation]) { 

         throw new TypeError("Unknown validation type"); 
        } 

        // Check the value. 
        isValid = validation[param.validation](data); 

        if (!isValid) { 

         throw new Error("object validation error on " + name); 
        } 

        // Assign the value. 
        // Some analytics methods accept numbers as strings so we check the return type. 
        switch (param.type) { 
         case "integer": 
          return data ? parseInt(data, 10) : null; 
         case "float": 
          return data ? parseFloat(data) : null; 
         case "boolean": 
          return data ? Boolean(data) : null; 
         case "currentloc": 
          return data; 
         default: 
          // Default to string. 
          return data ? data + "" : null; 
        } 

       }, 
       createArgs: function() { 

        var binder = this, 
         event = this.event, 
         args = $.map(event, function (val, key, pageLoc) { 
          var pageLoc = $(location).attr('href'); 


          var value; 

          if (key === "event") { 
           // We don't want to check for the event property in the DOM. 
           value = val.value; 

          } else { 

           // Validate and return the correct value from the DOM. 
           value = methods.validate.call(binder, val, key, pageLoc); 

          } 

          return value; 
         }); 

        return args; 
       } 
      }, 

      gaa = function (element, options) { 

       this.$element = $(element); 
       this.options = $.extend({}, $.fn.gaa.defaults, options); 
      }; 

      gaa.prototype = { 
       constructor: gaa, 
       trackEvent: function() { 
        var trackedEvent = $.Event("tracked.ga"); 
        var currentLoc = $(location).attr('href'); 

        this.args = methods.createArgs.call(this); 

        if (this.options.logit) { 

         if (window.console && window.console.log) { 

          // Push the data. 
          console.log("pushing to Google analytics", this.args); 
          this.$element.trigger(trackedEvent).trigger(currentLoc); 

          // this.$element.trigger(currentLocation); 

         } 
        } else { 

         var gaq = window._gaq; 

         if (gaq) { 

          // Set the context for our deferred callback. 
          var binder = this; 

          // Push the data. 
          $.when(gaq.push(args)).done(

          function() { 

           this.$element.trigger(trackedEvent); 

           // this.$element.trigger(trackedEvent); 


           // Redirect the location - delayed so that any other page functionality has time to run. 
           setTimeout(function() { 
            var href = binder.attr("href"); 

            if (href && href.indexOf("#") !== 0) { 
             window.location = href; 
            } 

           }, 100); 
          }); 

         } else { 
          throw new ReferenceError(" _gaq not there"); 
         } 
        } 
       } 

      }; 

      // wrapper definition 
      $.fn.gaa = function (options) { 
       return this.each(function() { 

        var $this = $(this), 
         data = $this.data("ga"), 
         opts = typeof options === "object" ? options : null; 


        if (!data) { 
         // Check the data and assign if not present. 
         $this.data("ga", (data = new gaa(this, opts))); 
        } 

        // Run the appropriate function is a string is passed. 
        if (typeof options === "string") { 

         data[options](); 

        } else { 

         var handler = data.options.handler.toLowerCase(), 
          // Check for the event attr here as it might be other than the default. 
          event = data.$element.attr("data-ga-event"); 

         // Overwrite if necessary. 
         $.extend(data.options, { 
          event: event 
         }); 

         // Build the data as we have nothing there. 
         // First assign the event. 
         data.event = $.gaaApi[data.options.event]; 

         // Then bind the handler. 
         if (handler === "load") { 

          data.trackEvent(); 

         } else { 

          data.$element.on(handler + ".ga", function (e) { 

           e.preventDefault(); 
           data.trackEvent(); 
          }); 
         } 
        } 
       }); 
      }; 

      // Define the defaults. 
      $.fn.gaa.defaults = { 
       event: ["trackEvent", "giveLocation"], 
       handler: "load", 
       logit: false 
      }; 

      // Set the public constructor. 
      $.fn.gaa.Constructor = gaa; 

      // Let's BEGIN 
      $(document).on("ready.ga", function() { 

       // Bind using the custom selector. 
       $(":ga").each(function() { 
        $(this).gaa(); 
       }); 
      }); 

     }(jQuery, window)); 


     // Set some options the ones below are the defaults. 
     var options = { 
      event: "trackEvent", // The event name unprefixed. 
      handler: "click", // The eventhandler to trigger the tracking. 
      // Using 'load' will track immediately. 
      logit: true, //to logit 

     }; 

     var options2 = { 
      event: "trackPageview", // The event name unprefixed. 
      handler: "click", // The eventhandler to trigger the tracking. 
      // Using 'load' will track immediately. 
      logit: true, //to logit 
     }; 

     var options3 = { 
      event: "trackPageview", // The event name unprefixed. 
      handler: "load", // The eventhandler to trigger the tracking. 
      // Using 'load' will track immediately. 
      logit: true //to logit 
     }; 

     // Binds using the custom selector. 

     $("load.trigger").gaa(options3); //fires a ga onload after domready 
     $("button.button1").gaa(options2).click(function() { 
      console.log('\nmore button events\n', 'heres the URL:', location.href) 
     }); 

     $("#clickme").gaa(options).click(function() { 
      $(this).toggleClass("changeIt"); 
     }); 


    }); 

index.html을

<load class="trigger">loading triggers ga event</load> 
<button class="button1">fire ga event with address</button> 
<button class="button1" id="clickme">multiple events</button> 

위치 바인드 여기 발생 및 JQuery와 제대로 위치를 소비 할 수 있습니다.

    event: { 
          value: ["trackPageview",$(location).attr('href')], 
          validation: "isString", 
          type: "string" 
         } 

이 방법을 사용하는 방법은 정확했지만 이전에 위치 정보를 가져와야합니다. 어쨌든이 형식처럼 보입니다.

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

올바른 방향으로 가야합니다.

이것은 재미있는 뇌물이었습니다. 그러면 나중에 필요할 때 location.href에 액세스 할 수 있습니다. 아이디어는 DOM 준비 후 _gaq 실행 전에 바인드를 형성하는 것입니다.

+0

더 많은 조사가 끝나면 location.href를 사용하여 원하는 URL 문자열을 반환해야합니다. – user2268663

+0

귀하의 코드가 내가 원하는 것을 정확히 수행 할 수 있을지 확실하지 않습니다. 나는'var the_cat = link.href'의 결과를 가져 와서 GA 코드의 'category'를 그 결과로 바꾸고 싶습니다. 예'_gaq.push ([ '_ trackEvent', the_cat, action, opt_label, opt_value, opt_noninteraction ']);'내가 당신을 오해하고 있다면 사과드립니다. 나는 이것에 관해 새로운 사람이다. 당신의 도움을 주셔서 감사합니다! – user2268663

+1

유사한 문제가있는 다른 사람들을 위해 나는이 링크를 발견하여 도움이되는 것들을 발견했습니다 : http://stackoverflow.com/questions/9275036/how-to-use-jquery-click-function-to-track-google- analytics-in-an-iframe – user2268663

관련 문제