How to find Tag Manager Container ID with JQuery

1.4k Views Asked by At

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));
}
2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

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).