Brian
Brian

Reputation: 340

Google Tag Manager - Not Set on Custom Javascript Occasionally

I set up a Google Tag to check what zip code my users are searching for. I used the Custom Javascript variable type to set up this variable.

 function() {
    var url = new URL({{Page URL}});
    var zip = url.searchParams.get("zip");
    return (zip);
  }

I triggered the tag when users went to an address containing "locations.aspx?term". Here is an example URL:

https://www.example.com/locations.aspx?term=64544&zip=64160&lat=43.3414758&lng=-0.1509269000000586

What should I be looking for to debug why 50% of the returns are (not set) in Google Analytics? The other half of the returns are coming back just fine.

Thanks!

Upvotes: 1

Views: 692

Answers (2)

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

While this does not address your JavaScript problems, GTM has a built-in way to get query parameters that in my experience is reliable and will probably solve your problem. You can use the URL variable type and change the "component type" setting from "Full URL" to "query", and enter your query key (the name of the url parameter). This will return the value of the parameter, or "undefined" if it doesn't exist.

get query GTM variable

Upvotes: 1

Victor Leontyev
Victor Leontyev

Reputation: 8736

There is two problems in your JS:

  • It is not supported in Internet Explorer
  • If url doesn't have querstring with zip params, it will return null. It will cause (not set)

Best way to do that is:

function () {
    function getURLParameter(name) {
        return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || "";
    }
    var zip = getURLParameter('zip');
    return zip;
}

Upvotes: 1

Related Questions