Skip to content

Commit 8bb9ef3

Browse files
committed
Add plugin for Matomo to track site search keywords
Use the plugins API for autocomplete, hook into the state change, retrieve the query term from the use, and send the query term together with the search results from the global context to Matomo. * autocomplete plugins: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/plugins/ * autocomplete state: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/state/ * autocomplete access data with context: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/context/ https://developer.matomo.org/guides/tracking-javascript-guide#internal-search-tracking Relates to #16
1 parent 1659562 commit 8bb9ef3

2 files changed

Lines changed: 29 additions & 0 deletions

File tree

packages/docsearch-react/src/DocSearchModal.tsx

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { AutocompleteState } from '@algolia/autocomplete-core';
22
import { createAutocomplete } from '@algolia/autocomplete-core';
33
import React from 'react';
44

5+
import { createMatomoPlugin } from './MatomoPlugin';
6+
57
import { MAX_QUERY_SIZE } from './constants';
68
import type { DocSearchProps } from './DocSearch';
79
import type { FooterTranslations } from './Footer';
@@ -125,6 +127,8 @@ export function DocSearchModal({
125127
[favoriteSearches, recentSearches, disableUserPersonalization]
126128
);
127129

130+
const matomoPlugin = createMatomoPlugin();
131+
128132
const autocomplete = React.useMemo(
129133
() =>
130134
createAutocomplete<
@@ -282,6 +286,7 @@ export function DocSearchModal({
282286
);
283287
});
284288
},
289+
plugins: [matomoPlugin],
285290
}),
286291
[
287292
typesenseCollectionName,
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import debounce from 'lodash/debounce';
2+
3+
declare global {
4+
interface Window {
5+
_paq: any;
6+
}
7+
}
8+
9+
function _matomoSiteSearch(query: string, hits: string) {
10+
var _paq = window._paq = window._paq || [];
11+
if (query.length > 0) {
12+
_paq.push(['trackSiteSearch', query, false, hits]);
13+
}
14+
}
15+
16+
var matomoSiteSearch_debounced = debounce(_matomoSiteSearch, 400);
17+
18+
export function createMatomoPlugin() {
19+
return {
20+
onStateChange({ state }) {
21+
matomoSiteSearch_debounced(state.query, state.context.nbHits);
22+
}
23+
};
24+
};

0 commit comments

Comments
 (0)