Google Analytics - Using GET instead of POST

2019-08-05 14:04发布

Ran into an issue where I need to use GET vs POST on a form method, but GATC cookie data is not being appended to the URL correctly, because the form's data is trumping Google's GATC data (using linkByPost).

I've read up on a potential solution posted here, but seems like an insane amount of work to make GET behave. I also stumbled upon another solution here, but IE doesn't respect anything after the 'anchor' portion of the url.

Anyone have any other ideas? If I can't handle this via JS, I will have to go into the script handling the form action and massage the querystring manually (assuming that GATC data is in $_REQUEST array). FTR, GATC data is not available via the $_REQUEST array, when using get.

2条回答
倾城 Initia
2楼-- · 2019-08-05 14:29

For future reference, in case anyone runs into the same issue, this is the solution I implemented. I lifted some code from the answer to this SO post, and combined it with the idea behind this post, where it localizes the GATC data, and adds hidden fields to the form for each one.

Resulting code:

$(document).ready(function() {
    $('#formId').submit(function(e) {

        try {

            e.preventDefault();

            var form = this;

            if (typeof _gat !== 'undefined') {

                _gaq.push(['_linkByPost', this]);

                var pageTracker = _gat._getTrackerByName();

                var url = pageTracker._getLinkerUrl(form.action);

                var match = url.match(/[^=&?]+\s*=\s*[^&#]*/g);

                for ( var i = match.length; i--; ) {

                    var spl = match[i].split("=");

                    var name = spl[0].replace("[]", "");

                    var value = spl[1];

                    $('<input>').attr({
                        type: 'hidden',
                        name: name,
                        value: value
                    }).appendTo(form);
                }
            }

            setTimeout(function() { form.submit(); }, 400);
        } catch (e) { form.submit(); }
    });
});
查看更多
冷血范
3楼-- · 2019-08-05 14:39

You can use jQuery serialize to get the form's elements, then _getLinkerUrl to append the cross-domain tracking data

$('#formID').submit(function(e) {
  var pageTracker = _gat._getTrackerByName();
  var url = this.action + '?' + $(this).serialize();
  url = pageTracker._getLinkerUrl(url);
  if (this.target != '_blank') location.href = url;
  else window.open(url);
});
查看更多
登录 后发表回答