Problem/Motivation
The google_tag Search API integration (\Drupal\google_tag\EventSubscriber\SearchApiSubscriber) listens to SearchApiEvents::PROCESSING_RESULTS and pushes a GA4 search event to the data layer every time the event fires:
public function onSearch(ProcessingResultsEvent $event) { $keys = $event->getResults()->getQuery()->getKeys(); if ($keys !== NULL) { ... $this->collector->addEvent('search', [ 'search_term' => implode(' ', $keys), ]); } }
EventCollector::addEvent() always appends to its events array:
public function addEvent(string $name, array $contexts = []): void { $event = $this->createEventInstance($name, $contexts); if ($event === NULL) { return; } $this->events[] = $event; }
But, a single Drupal Views page can render several displays (e.g. a default page display plus multiple attachment block displays) that each execute their own query against the same Search API index with the same search keys. Each of those queries dispatches SearchApiEvents::PROCESSING_RESULTS again, so onSearch() runs once per display, and the search GA4 event gets pushed to the data layer once per display, not once per actual user search.
This was causing the `search` event, on one of our websites, to be fired 5 times per page request, consecutively , and all with the exact same parameters :p
Steps to reproduce
- Install and configure
google_tagwith thesearchevent enabled. - Create a Search API View with a default page display, and add one or more additional displays (attachment or block) to the same View that render together on the same page.
- Perform a search and inspect the
dataLayerarray in the browser. - The same
searchevent is pushed multipled times (once per display), instead of once per user search.
Proposed resolution
Guard SearchApiSubscriber::onSearch() so it only pushes the search event once per request, regardless of how many displays for the same search view are in the page.
Remaining tasks
Make sure event won't fire more than once on the same request.
| Comment | File | Size | Author |
|---|---|---|---|
| #3 | 3612054-3-multiple-search-events.patch | 1.44 KB | gueguerreiro |
Issue fork google_tag-3612054
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
Comment #3
gueguerreiroI opened a merge request with the fix, for review.
I'm also attaching a local patch, if it's easier to use for composer.json like that instead.
Comment #5
japerryConfirmed the bug on 2.0.x. Looking at MR !142, the per-request flag also drops a later search on the same page with different keys (e.g. a header search block plus a product search), and which one gets picked depends on render order. I rebased it onto 2.0.x and pushed a follow up commit: