firebase-js-sdk
firebase-js-sdk copied to clipboard
Unable to use custom dataLayerName when multiple copies of gtag.js exist
[REQUIRED] Describe your environment
Operating System version: MacOS 12.4 Browser version: Brave v1.42.97 Firebase SDK version: 9.9.2 Firebase Product: Analytics
[REQUIRED] Describe the problem
I'm using Firebase Analytics on a web site that loads multiple copies of gtag.js with different tracking/measurement IDs, i.e. if I look at the DOM for the site I see several script tags like
<script async src="https://www.googletagmanager.com/gtag/js?id=XXXXXXX"/>
The problem is that if I want to use a custom data layer name, the gtag script tag also needs to have the custom data layer name passed in via a query parameter, &l=custom_datalayer_name
. Firebase, won't add a new script tag if one already exists, even if the l query param is different.
It's evident looking at initialize-analytics.ts that the call to findGtagScriptOnPage
doesn't take the dataLayerName into account.
// Detect if user has already put the gtag <script> tag on this page.
if (!findGtagScriptOnPage()) {
insertScriptTag(dataLayerName, dynamicConfig.measurementId);
}
Steps to reproduce:
- Have an HTML file that has a gtag script
- Load a module that initializes firebase analytics and uses settings to customize the data layer name
- Observe that there's no new gtag
- Log an event
- Observe in GA debugger that nothing is sent
Now remove the gtag
- Observe that firebase correctly creates a script tag with the l query param
- Log an event
- Observe the event is sent
Alternatively, remove the settings call with custom dataLayerName and events work too regardless of whether the script tag is present.
Relevant Code:
<html>
<head>
<script src="https://www.googletagmanager.com/gtag/js?l=datalayer&id=G-XXXXX" async=""></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'XXXXX');
</script>
</head>
<body>
...
</body>
</html>
const app = initializeApp(firebaseConfig);
settings({ gtagName: "custom_gtag", dataLayerName: "custom_datalayer" });
const analytics = getAnalytics(app);
logEvent(analytics, "test_event");
I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.
I have one question to ask, we've had complaints in the past from users when gtag was accidentally loaded twice due to a bug, that they got an error in the console (I think only when using the Google Analytics Debugger). Does a second loading of gtag, with a new datalayer name, cause any problems when you do it manually?
I have seen first-hand a number of sites with a half-dozen copies of gtag loaded without error. Usually they just differ in id. Less commonly do I see the dataLayer modified, but in my own testing it hasn't caused any noticeable error, even with the GA debugger.
The feature has been released in v9.12.0.