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
- Enable google_tag with any container, so the gtag libraries are attached.
- Add a
GoogleTagEventCommandfollowed by aRedirectCommand
to the AjaxResponse of any Ajax-submitted form. - Visit the site with uBlock Origin enabled (default lists) and submit the form.
- 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
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:
- google_tag-3618810
changes, plain diff MR !147
- 3618810-gtagevent-ajax-command
changes, plain diff MR !146
Comments
Comment #3
kgaut commentedComment #6
japerryConfirmed the bug, and added a test. Made a few nit cleanups and fixed!