Skip to content

Commit

Permalink
feat: add a callback to know when the script does not load (#125)
Browse files Browse the repository at this point in the history
* feat: add a callback to know when the script does not load

* docs: Update README.md

---------

Co-authored-by: Julien Bouquillon <julien.bouquillon@beta.gouv.fr>
  • Loading branch information
totakoko and revolunet committed Apr 19, 2024
1 parent 60b78c5 commit 04bf826
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ The function has three optional callback properties that allow for custom behavi

- `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.**

- `onScriptLoadingError`: This callback is triggered when the script does not load. It does not receive any parameters. useful to detect ad-blockers.

## Tests

```
Expand Down
7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ interface InitSettings {
onRouteChangeStart?: (path: string) => void;
onRouteChangeComplete?: (path: string) => void;
onInitialization?: () => void;
onScriptLoadingError?: () => void;
nonce?: string;
trustedPolicyName?: string;
logExcludedTracks?: boolean;
Expand Down Expand Up @@ -81,6 +82,7 @@ export function init({
onRouteChangeStart = undefined,
onRouteChangeComplete = undefined,
onInitialization = undefined,
onScriptLoadingError = undefined,
nonce,
trustedPolicyName = "matomo-next",
logExcludedTracks = false
Expand Down Expand Up @@ -137,6 +139,11 @@ export function init({
scriptElement.defer = true;
const fullUrl = `${url}/${jsTrackerFile}`;
scriptElement.src = sanitizer.createScriptURL?.(fullUrl) ?? fullUrl;
if (onScriptLoadingError) {
scriptElement.onerror = () => {
onScriptLoadingError()
}
}
if (refElement.parentNode) {
refElement.parentNode.insertBefore(scriptElement, refElement);
}
Expand Down

0 comments on commit 04bf826

Please sign in to comment.