Problem/Motivation

The gtagEvent Ajax command defined in js/gtag.ajax.js calls
gtag() unconditionally:

Drupal.AjaxCommands.prototype.gtagEvent = function (ajax, response) {
  gtag('event', response.event_name, response.data);
};

The gtag() function is defined by js/gtag.js, which is attached
with preprocess: false and therefore always served under its own file name
(/modules/contrib/google_tag/js/gtag.js), excluded from JS aggregation.
Most content blockers (uBlock Origin, Adblock Plus, Brave shields…) match the
gtag.js file name through EasyPrivacy filter lists and block that request.

When that happens, gtag is never defined, but gtag.ajax.js
(which IS aggregated, so not blocked) still registers the Ajax command. Any server-side
code adding a GoogleTagEventCommand to an AjaxResponse then makes
the whole Ajax response fail for those visitors:

ReferenceError: gtag is not defined

Because Ajax commands are executed in order, every command queued after the
gtagEvent one (e.g. a RedirectCommand after a login form
submission) is never executed. A tracking call — pointless for a visitor who blocks
analytics anyway — ends up breaking site functionality for a significant share of users.

Steps to reproduce

  1. Enable google_tag with any container, so the gtag libraries are attached.
  2. Add a GoogleTagEventCommand followed by a RedirectCommand
    to the AjaxResponse of any Ajax-submitted form.
  3. Visit the site with uBlock Origin enabled (default lists) and submit the form.
  4. The Ajax error dialog shows "ReferenceError: gtag is not defined" and the redirect
    never happens.

Proposed resolution

Guard the Ajax command: if gtag is not a function, return without doing
anything instead of throwing. The event is lost, but it could not have been sent anyway,
and the rest of the Ajax response keeps working.

Remaining tasks

Review.

API changes

None.

Issue fork google_tag-3618810

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

kgaut created an issue. See original summary.

kgaut’s picture

Status: Active » Needs review

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

japerry’s picture

Status: Needs review » Fixed

Confirmed the bug, and added a test. Made a few nit cleanups and fixed!

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 218eb01b on 2.0.x authored by kgaut
    fix: #3618810 Guard the gtagEvent Ajax command when gtag.js is blocked
    

Status: Fixed » Closed (fixed)

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