diff --git a/README.md b/README.md index f1b3635..307032f 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ function MyApp({ Component, pageProps }) { useEffect(() => { init({ url: MATOMO_URL, siteId: MATOMO_SITE_ID }); }, []); - + return ; } @@ -67,6 +67,16 @@ import { push } from "@socialgouv/matomo-next"; push(["trackEvent", "contact", "click phone"]); ``` +### Extensibility + +The function has three optional callback properties that allow for custom behavior to be added: + +- `onRouteChangeStart(path: string) => void`: This callback is triggered when the route is about to change with Next Router event `routeChangeStart`. It receives the new path as a parameter. + +- `onRouteChangeComplete`: This callback is triggered when the route change is complete with Next Router event `routeChangeComplete`. It receives the new path as a parameter. + +- `onInitialization`: This callback is triggered when the function is first initialized. It does not receive any parameters. **It could be useful to use it if you want to add parameter to Matomo when the page is render the first time.** + ## Tests ``` diff --git a/src/__tests__/matomo.test.ts b/src/__tests__/matomo.test.ts index 0afbd22..1c11858 100644 --- a/src/__tests__/matomo.test.ts +++ b/src/__tests__/matomo.test.ts @@ -101,6 +101,21 @@ describe("push", () => { }); }); +describe("onInitialization", () => { + test("should work if the surcharge of the operator", () => { + init({ + onInitialization: () => { + push(["during_initialization", "hello"]); + }, + siteId: "42", + url: "YO", + }); + expect(window._paq).toEqual( + expect.arrayContaining([["during_initialization", "hello"]]) + ); + }); +}); + describe("router.routeChangeStart event", () => { beforeEach(() => { global._paq = []; diff --git a/src/index.ts b/src/index.ts index 6fd4e4f..8df0d7f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,7 @@ interface InitSettings { excludeUrlsPatterns?: RegExp[]; onRouteChangeStart?: (path: string) => void; onRouteChangeComplete?: (path: string) => void; + onInitialization?: () => void; } interface Dimensions { @@ -65,6 +66,7 @@ export function init({ excludeUrlsPatterns = [], onRouteChangeStart = undefined, onRouteChangeComplete = undefined, + onInitialization = undefined, }: InitSettings): void { window._paq = window._paq !== null ? window._paq : []; if (!url) { @@ -89,6 +91,8 @@ export function init({ push(["setTrackerUrl", `${url}/${phpTrackerFile}`]); push(["setSiteId", siteId]); + if (onInitialization) onInitialization(); + /** * for initial loading we use the location.pathname * as the first url visited.