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));
}
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:
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.
It's close, but we have to modify it to allow us to pass in our own query string:
Now we can use it to find the
id
value, which should be your container ID:You will need to run this after the tag manager itself loads.