0

I need to find what the Google Tag Manager container ID is after the page loads.

I cannot get it from the same source as i'm adding it to the page.

i want to set a jQuery variable to GTM-XXXXXX

i have been messing with

var scripts = $("script");

but this is returning an array, and these are subject to an order change so i don't think it is too reliable

UPDATE 1:

am using the following to successfully return container ID, it just feels way to flaky and wrong

var scripts = $("script");

if (scripts.length) {
  console.log(scripts[2].src.substring(42, 52));
}
ddools
  • 135
  • 2
  • 9
  • Is it your site? Wouldn't you know the container ID in order to set it up? – Cᴏʀʏ Jun 17 '15 at 13:59
  • It is, but we use different container ID's for different domains. i can output what i'm putting in at source, but i need to output what loads on page load – ddools Jun 17 '15 at 14:07

2 Answers2

2

This is untested, but you could maybe look for something better about the script that identifies the tag manager, such as part of the URL. Let's get the full source URL for the script that loads:

var tagManagerUrl = $('script[src*="googletagmanager"]').attr('src');

Now you have the URL whose query string contains the ID, but we need a way to parse the query string value from it. Let's take a look at the code from this answer, which gets a query string value by name from the current location.

function getParameterByName(name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

It's close, but we have to modify it to allow us to pass in our own query string:

function getParameterByName(qs, name) {
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(qs);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

Now we can use it to find the id value, which should be your container ID:

var tagManagerContainerId = getParameterByName(tagManagerUrl.split('?')[1], 'id');
// do something with it

You will need to run this after the tag manager itself loads.

Community
  • 1
  • 1
Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
1

While Cory's answer is great I don't think you need jQuery at all, since in most scenarios it would even be simpler to use the container id variable (needs to be enabled in the variables section of the interface) in GTM and run the javascript function from inside a custom HTML tag:

<script>
console.log({{Container ID}});
</script>

(although I admit that does not answer the question of how to do this with jQuery).

Eike Pierstorff
  • 31,996
  • 4
  • 43
  • 62