Problem/Motivation

When entering a Google Tag ID in the Google Analytics recommended recipe (Google Tag module configuration), whitespace is currently allowed.

If a user accidentally includes a leading or trailing space (e.g. when pasting a GTM Container ID like GTM-XXXXXX), this is passed through to the rendered <script> tag. (When a user highlights the GTM ID in Google Tag Manager, an initial space is included when copying the value.)

The space results in an invalid script URL and breaks tag loading, leading to confusing and difficult-to-diagnose errors.

For example:

<script async src="https://www.googletagmanager.com/gtm.js?id= GTM-XXXXXXX" type="text/javascript"></script>

Notice the space after id= in the src string.

Steps to reproduce

  1. Install Drupal CMS
  2. Turn off JS Aggregation so that we can see the individual script tags for troubleshooting. (Configuration > Development > Performance > Aggregation > Toggle off JS Aggregation)
  3. Go to Google Tag Manager and create a new container for a website.
    • Select "Web" as the target platform.
    • After creation, note the Container ID (formatted like GTM-XXXXXXX)
  4. Go to Google Analytics and create a new GA4 property for the same site. This step is optional for reproducing the bug, but is typically done in real-world usage when configuring Google Analytics via GTM.
  5. In Drupal CMS, install the Google Analytics recommended add-on (recipe). (Extend > Recommended > Google Analytics > Install or Reinstall). This will install the Google Tag module and prompt for a Google Tag ID at admin/config/services/google-tag.
  6. In Google Tag Manager, copy the container ID on the Workspace tab > Overview page. Paste the GTM Container ID into the Google Tag ID field. For me, an initial space was included when I pasted. To reproduce the bug, ensure there is a space before the GTM ID.
  7. Visit the front page of the site and log out. Return to the front page.
  8. When the Klaro privacy consent window pops up, click Customize. Toggle on all categories so that the Google Analytics cookies will be visible. (Only functional cookies are enabled by default.)
  9. Inspect source and look for the following tag:
    <script async src="https://www.googletagmanager.com/gtm.js?id= GTM-XXXXXXX" type="text/javascript"></script>
  10. Notice the space after the id in the src string.

Proposed resolution

See web/modules/contrib/google_tag/js/gtm.js (lines 23-30). The passed-in tagId variable uses user input which can include a leading space, which would break the URL and cause the Google Tags not to be found. Strip leading/trailing whitespace from tagId before interpolating it in the script.src string.

User interface changes

None

Issue fork google_tag-3523282

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

amber himes matz created an issue. See original summary.

amber himes matz’s picture

Issue summary: View changes
amber himes matz’s picture

Issue summary: View changes
phenaproxima’s picture

Validation can be extremely tricky for recipe inputs, because the default value has to fulfill the constraints too. Unfortunately, something like Google Tag really doesn't have a valid default value -- it's effectively a unique API key. So that's why it doesn't have constraints right now. If we added the wrong kind of constraint, Project Browser would immediately throw an exception if someone tried to apply the recipe.

Additionally, recipes don't support input transformation (at least, not yet they don't).

All that being said, we could validate that the tag ID doesn't contain whitespace (an empty string would still pass that constraint). We just can't actively strip it out, unless we do some Form API trickery -- but that would require a shim module.

amber himes matz’s picture

My perspective is from the documentation writer's point of view. To have to say, "Make sure you don't have any leading or trailing spaces when you enter your GTM ID" in documentation for setting up analytics is weird to me. That just smacks of a programmer's problem, not a user's problem.

Since the Google Tag module is responsible for constructing the string for the script tag's src attribute, maybe this issue would be better filed in their queue instead. And instead of suggestion validation, suggesting trimming leading/trailing whitespace from the tagId variable.

web/modules/contrib/google_tag/js/gtm.js, lines 23-30:

config.tagIds.forEach(function (tagId) {
    const script = document.createElement('script');
    script.async = true;
    const dLink = dl != 'dataLayer' ? `&l=${dl}` : '';
    script.src = `https://www.googletagmanager.com/gtm.js?id=${tagId}${gtm_environment}${dLink}`;
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
  });

@phenaproxima Ok with me to close as won't fix and I'll file it in the Google Tag module's queue instead.

phenaproxima’s picture

Sure, that sounds good. We could also just repurpose this issue and move it to Google Tag's queue, so they have the context for why we're doing this.

amber himes matz’s picture

Title: Add validation to Google Tag ID input to remove initial/trailing spaces when applying Google Analytics recipe » Remove leading and trailing whitespace of tagId for script.src string in js/gtm.js
Issue summary: View changes

Updated title and issue summary.

I'm not sure how to move this to another project's queue. Could use some help with that.

amber himes matz’s picture

Issue summary: View changes
phenaproxima’s picture

Project: Drupal CMS development repository » Google Tag
Version: » 2.0.x-dev
Component: Track: Analytics » Code

Fixed. :) The "Project" field in the issue metadata is where you control that.

amber himes matz’s picture

Thanks! I just saw that a moment too late.

penyaskito’s picture

Maybe this could happen on preSave instead of the rendering?

Actually, the recipe validates with:

      Regex: '/^(?:GT|UA|G|AW|DC|GTM)-[0-9a-zA-Z]{4,}(?:-[0-9]{1,})?$/'

Wouldn't that be enough?

EDITED: I had an old checkout. See #3498929: ValidationFailedException when applying the analytics recipe.

penyaskito’s picture

Even if we still want this fixed in Google Tag, this would alleviate the issue on the Drupal CMS recipe with HTML5 validation:

    form:
      '#type': 'textfield'
      '#title': 'Google Tag ID'
+      '#pattern': '/^(?:GT|UA|G|AW|DC|GTM)-[0-9a-zA-Z]{4,}(?:-[0-9]{1,})?$/'
      '#description': "The Google Tag ID for tracking. This ID is unique to each site you want to track separately, and must be in the form of GT-xxxxxx, G-xxxxxxxx, AW-xxxxxxxxx, GTM-xxxxxxxx or DC-xxxxxxxx."

japerry made their first commit to this issue’s fork.

japerry’s picture

Status: Active » Fixed

Added trim to both the reading of the config entity, as well as the form. Also added kernel tests for all three.

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

  • japerry committed f8fb75d6 on 2.0.x
    fix: #3523282 Trim whitespace from tag IDs
    

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.