Giter VIP home page Giter VIP logo

matomo-tracker's People

Contributors

aditudorache avatar an-dz avatar annablgkv avatar aryanj-nyc avatar bassosimone avatar chrisvanmook avatar codebymikey avatar dependabot-preview[bot] avatar dependabot[bot] avatar dunklestoast avatar evestera avatar geier1993 avatar janjaap avatar jonkoops avatar juliobetta avatar lennart avatar lgp171188 avatar m4tt72 avatar nesk avatar piotr-cz avatar qgadrian avatar robinpiets avatar royderks avatar sassninja avatar thiagoarrais avatar thomasm0 avatar timvanoostrom avatar vladislavyeremeyev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

matomo-tracker's Issues

Feature request: Easy way to disable the tracker (without triggering exceptions)

Problem
We deploy the same app to several different environments. Some of which we can do tracking in, and some where we can not, so we need a way to disable the tracker.

Possible solution
If an option is added to initialization that if set turns all tracking calls into no-ops, only the initialization code needs to care if tracking is enabled or not.

Alternatives
We could handle this outside the library, but that would necessitate checks everywhere tracking calls are made (or a whole layer on top of the library).

We could provide initalization with an invalid URL for the tracker script and just let it fail, but this seems like a hack, and we would prefer to avoid adding meaningless errors to logs.

Additional notes
I'll post a PR shortly with one possible implementation, for your consideration.

Redundant paq pushes

Describe the bug
The Tracker pushes multiple time the page title as well as the url.

To Reproduce
Steps to reproduce the behavior:

  1. Use trackEvent, trackPageView and trackEcommerceOrder in arbitrary order.
  2. inspect the window._paq

Expected behavior
It should be pushed exactly one time.

Additional context
The behaviour is located in the tracker.

TypeError: pushInstruction is not a function

Describe the bug
I'm trying to push the UserId up to matomo

To Reproduce
In react functional component

const { pushInstruction } = useMatomo();

useEffect(() => {
   pushInstruction('setUserId', userHome);
 }, [userHome])

I want to push the userID up similar to what I do with tracking but it's not working.
I don't see pushInstruction referenced in matomo-tracker-js/lib/useMatomo.d.ts/ like the other functions (trackPageView, trackLink etc.)

Unhandled Runtime Error
TypeError: pushInstruction is not a function

Support for Angular

Is your feature request related to a problem? Please describe.

N/A

Describe the solution you'd like

Support for Angular.

Describe alternatives you've considered

N/A

Additional context

Currently, there is no up to date Matomo implementation for Angular. Would you consider adding such to this repository as the setup seems convenient?

Change the API to improve initialisation

Instead of passing an object, it would be nice to have something like this instead:

instance
    .urlBase('https://LINK.TO.DOMAIN')
    .siteId(3)
    .setUserId('example_id')
    .disableCookies()
    .setSecureCookie(true)
    .setRequestMethod('POST');

#174 (comment)

Global object (window) confusion

Describe the bug

Readme states that MatomoTracker instance may be initialized like so

import MatomoTracker from '@datapunt/matomo-tracker-js'
const MatomoInstance = new window.MatomoTracker({})

and later uses syntax without window:

import MatomoTracker from '@datapunt/matomo-tracker-js'
const MatomoInstance = new MatomoTracker({})

however latter doesn't work (at least in rollup builds) as it holds es-module wrapper {__esModule: true, default: ƒ}.

Same object is also leaking via window.MatomoTracker_1.

IMHO it's not necessary to set class on window object, as it's already exported via IIFE in rollup config.

To Reproduce
As in description

Expected behavior
When importing MatomoTracker it's possible to initialize it via new MatomoTracker({}).
The window.MatomoTracker property is available when using ES5 prebuilt bundle.min.js.

Screenshots
N/A

Desktop (please complete the following information):
N/A

Smartphone (please complete the following information):
N/A

Additional context
Proposed solution:

  • remove code block responsible for setting global object
  • to preserve semver backward compatibility release in v1.x
  • fix readme so examples are consistent

When running yarn run build, rollup shows warnings related to this issue:

src/index.ts → bundle.min.js...
(!) Mixing named and default exports
https://rollupjs.org/guide/en/#output-exports
The following entry modules are using named and default exports together:
src\index.ts

Consumers of your bundle will have to use chunk['default'] to access their default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning

This is caused by exporting both default and named exports together in index.ts:

export default MatomoTracker

export { types }

I wonder do we need to export types (here)?

I'd recommend removing types from index.ts and defining in package.json

{
  "main": "lib/index.js",
  "types": "lib/types.ts"
}

Related commit: c6c2324

Is there any way to globally set a custom dimension value?

I am using matomo-tracker-react to analyse a react single page app. The app is evolving continuesly and I use a custom dimension to detect what version of the app the user is using.

Currently I do it like this in my main router:

import {useMatomo} from "@datapunt/matomo-tracker-react";

const Router = () => {
    const {pushInstruction} = useMatomo();

    useEffect(() => {
        pushInstruction('setCustomDimension', 1, process.env.REACT_APP_VERSION);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    ...

But I would like to be able to do something like this:

import { MatomoProvider, createInstance } from "@datapunt/matomo-tracker-react"
const instance = createInstance({
    urlBase: process.env.REACT_APP_MATOMO_URL_BASE,
    siteId: process.env.REACT_APP_MATOMO_SITE_ID,
    customDimensions: [{ // <<<<<< maybe something like this?
        id: 1,
        value: process.env.REACT_APP_VERSION
    }]
});

Elements not defined

Hello there, and thank you for your work.
I've follow the steps on the doc and I have these erros... :/
I did the 2 first steps after "usage" for react.

Failed to compile

./src/js/components/modules/dashboard/Dashboard.jsx
  Line 10:6:   "loading" is not defined      no-undef
  Line 13:3:   "doSomething" is not defined  no-undef
  Line 19:10:  "Button" is not defined       react/jsx-no-undef

Search for the keywords to learn more about each error.

In my index.js

const instance = createInstance({
	urlBase: "https://stats.level-up.education/",
	siteId: 2, // optional, default value: `1`
});

ReactDOM.render(
	<MatomoProvider value={instance}>
		<Root/>
	</MatomoProvider>,
	document.getElementById('root')
);

And for the component I just took yours (in the doc).

Thank you.

matomo-tracker-js, bundle.min.js - not found

Describe the bug
matomo-tracker-js, bundle.min.js - not found.

Hello, In release v0.2.0, was dropped auto build bundle.min.js file for matomo-tracker-js. How can I build this file without fork all repository and build js part through common package.json ?

Refresh or reset React context instance to track logged users

I have a React frontend where users have to log in. The tracking instance is created one the user is logged in with userId corresponding to user's first name and last name.

When user A logs out then user B logs in, Matomo backend still track events for user A

Describe the solution you'd like
How to programatically refresh or reset the Matomo Instance / Context?

Additional context
This is my Matomo tracker Provider:

export const TrackingWrapper = ({ children }: { children: React.ReactNode }) => {
  const [{ firstName, lastName }] = useContext(UserContext); 

  const trackerInstance = useMemo(
    () =>
      createInstance({
        urlBase: MATOMO_TRACKER_URL,
        userId: `${firstName}  ${lastName}`, // Will change on different user log out / log in
        siteId: 1,
        linkTracking: false,
        configurations: {
          disableCookies: true,
        },
      }),
    [firstName, lastName]
  );

  return <MatomoProvider value={trackerInstance}>{children}</MatomoProvider>;
};

Missing ecommerce actions

Is your feature request related to a problem? Please describe.
Currently not all ecommerce actions of matomo are supported.
The full list can be found here:
https://developer.matomo.org/api-reference/tracking-javascript

Describe the solution you'd like
The missing ones should be added to allow using all possible ecommerce actions

  • removeEcommerceItem
  • clearEcommerceCart

Additional context
https://github.com/Amsterdam/matomo-tracker/blob/master/packages/js/src/MatomoTracker.ts

pushInstriction type mismatch. Could reuse MatomoInstance interface

Is your feature request related to a problem? Please describe.
I'd like to use MatomoInstance consistently. useMatomo hook returns type not matching with the return type of createInstance.

I'd like to pass matomo client returned by useMatomo as typed by MatomoInstance.

Describe the solution you'd like

MatomoProvider takes MatomoInstance as a value which is defined as:

export interface MatomoInstance {
    trackEvent: MatomoTracker['trackEvent'];
    trackEvents: MatomoTracker['trackEvents'];
    trackPageView: MatomoTracker['trackPageView'];
    trackSiteSearch: MatomoTracker['trackSiteSearch'];
    trackLink: MatomoTracker['trackLink'];
    pushInstruction: MatomoTracker['pushInstruction']; // which resolves to pushInstruction(name: string, ...args: any[]): MatomoTracker;
}

, but useMatomo returns very close type, but different:

declare function useMatomo(): {
    trackEvent: (params: TrackEventParams) => void | undefined;
    trackEvents: () => void | undefined;
    trackPageView: (params: TrackPageViewParams) => void | undefined;
    trackSiteSearch: (params: TrackSiteSearchParams) => void | undefined;
    trackLink: (params: TrackLinkParams) => void | undefined;
    enableLinkTracking: () => void;
    pushInstruction: (name: string, ...args: any[]) => void;
};

The difference:

Argument of type '{ trackEvent: (params: TrackEventParams) => void | undefined; trackEvents: () => void | undefined; trackPageView: (params: TrackPageViewParams) => void | undefined; trackSiteSearch: (params: TrackSiteSearchParams) => void | undefined; trackLink: (params: TrackLinkParams) => void | undefined; enableLinkTracking: () =...' is not assignable to parameter of type 'MatomoInstance'.
  The types returned by 'pushInstruction(...)' are incompatible between these types.
    Type 'void' is not assignable to type 'MatomoTracker'.

Why not have simply

declare function useMatomo(): MatomoInstance;

Describe alternatives you've considered

I defined my own interface with a subset of functions I'm using:

export interface MatomoTracker {
  trackEvent: (params: TrackEventParams) => void | undefined;
}

But it only works because I'm not using pushInstruction I believe.

Additional context
Using version "0.3.1", updated to 0.5.1 but the types are defined still in the same way.

Integrate it with react.Router history

Is your feature request related to a problem? Please describe.
I was expecting this lib to integrate with React Router out of the box, such as https://github.com/guillaumeparis2000/react-piwik :

<Provider store={store}>
    <Router routes={routes} history={piwik.connectToHistory(history, trackAtConnect)} />
  </Provider>,

Describe the solution you'd like
I'd like sth similar as above or at least a README on how to listen to history events and track pageViews on history changes.

Describe alternatives you've considered
Choosing another lib or implementing it myself.

Recording userId using setUserId

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

trackGoal Matomo feature - Manually trigger goal conversions

Is your feature request related to a problem? Please describe.
It would be awesome to be able to use the trackGoal method of matomo with the javascript tracker

Describe the solution you'd like
afaik, matomo supports the manually trigger goal conversions via the trackGoal keyword.
By default, Goals in Matomo are defined as "matching" parts of the URL (starts with, contains, or regular expression matching).
I do not know if there is a method that can mimic this in the library, but it would be very helpful, mostly for SPAs without routing, where one cannot use the matomo track goal utilities

Module Warning & Failed to parse source map error when used with Create React App v5.0.0 with Typescript

Describe the bug
I recently updated my project which uses CRA to v5.0.0.
But when I start the project. I get the following warnings.
Though tracking is working fine I just wanted to flag this warnings.

WARNING in ./node_modules/@datapunt/matomo-tracker-js/es/MatomoTracker.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/MatomoTracker.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/MatomoTracker.ts'
 @ ./node_modules/@datapunt/matomo-tracker-js/es/index.js 1:0-44 3:15-28
 @ ./node_modules/@datapunt/matomo-tracker-react/es/instance.js 1:0-56 4:13-26
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 3:0-55 3:0-55
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-js/es/constants.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/constants.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/constants.ts'
 @ ./node_modules/@datapunt/matomo-tracker-js/es/MatomoTracker.js 12:0-42 183:15-38 202:15-39 216:25-47 223:13-35 268:13-46 276:25-64
 @ ./node_modules/@datapunt/matomo-tracker-js/es/index.js 1:0-44 3:15-28
 @ ./node_modules/@datapunt/matomo-tracker-react/es/instance.js 1:0-56 4:13-26
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 3:0-55 3:0-55
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-js/es/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/index.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/index.ts'
 @ ./node_modules/@datapunt/matomo-tracker-react/es/instance.js 1:0-56 4:13-26
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 3:0-55 3:0-55
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-js/es/types.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/types.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-js/src/types.ts'
 @ ./node_modules/@datapunt/matomo-tracker-js/es/index.js 2:0-33 4:0-17
 @ ./node_modules/@datapunt/matomo-tracker-react/es/instance.js 1:0-56 4:13-26
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 3:0-55 3:0-55
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-react/es/MatomoContext.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/MatomoContext.tsx' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/MatomoContext.tsx'
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 1:0-59 1:0-59
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-react/es/MatomoProvider.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/MatomoProvider.tsx' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/MatomoProvider.tsx'
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 2:0-61 2:0-61
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-react/es/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/index.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/index.ts'
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-react/es/instance.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/instance.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/instance.ts'
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 3:0-55 3:0-55
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-react/es/useMatomo.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/useMatomo.ts' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/useMatomo.ts'
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 4:0-51 4:0-51
 @ ./src/index.tsx 24:0-64 52:33-47

WARNING in ./node_modules/@datapunt/matomo-tracker-react/es/utils/useOutboundClickListener.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/utils/useOutboundClickListener.tsx' file: Error: ENOENT: no such file or directory, open '/Users/nick/project-cra-5/node_modules/@datapunt/matomo-tracker-react/src/utils/useOutboundClickListener.tsx'
 @ ./node_modules/@datapunt/matomo-tracker-react/es/useMatomo.js 3:0-72 14:6-30
 @ ./node_modules/@datapunt/matomo-tracker-react/es/index.js 4:0-51 4:0-51
 @ ./src/index.tsx 24:0-64 52:33-47


10 warnings have detailed information that is not shown.
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.

webpack 5.65.0 compiled with 10 warnings in 93372 ms

No issues found.

To Reproduce
Steps to reproduce the behavior:
Create a new project with create-react-app v5 with typescript
Add Matomo dependencies
Configure matomo instance
yarn start / npm start

Also, you can fork from the sandbox and test it on your local
https://codesandbox.io/s/7ner9

Expected behavior
I think this warning should be fixed

Thanks!

Plans on integrating Matomo's Formanalytics capabilities?

Hi there,

thanks for providing such a convenient wrapper for tracking React-SPAs.
We are currently trying to figure out how to make us of matomo's form analytics to capture insights on how our forms are used.

As far as I could tell, the react-tracker package doesn't support Matomo's form analytics APIs yet, is that correct? If so, are there any future plans to integrate these so that they can be called from the useMatomo hook?

Best regards,

Tracking & Cookie Consent

Hey there,

I was wondering if someone could tell me how to set requireConsent?
I tried to add it to the configuration object in createInstance but somehow it doesn't work.

Thanks

Add support for SSR

In order to make sure we can track page views of pages that are both server-side rendered and client-side rendered we need to come up with a plan to allow our code to run in both environments.

Do not require urlBase and siteId if matomo is disabled

I have urlBase: '', siteId: '', disabled: true, but I'm getting the following

Error: Matomo urlBase is required.
new MatomoTracker
src/MatomoTracker.ts:20
  17 |     }
  18 |     if (!userOptions.siteId) {
  19 |         throw new Error('Matomo siteId is required.');
> 20 |     }
     | ^  21 |     this.initialize(userOptions);
  22 | }
  23 | initialize({ urlBase, siteId, userId, trackerUrl, srcUrl, disabled, heartBeat, linkTracking = true, configurations = {}, }) {
View compiled
createInstance
src/instance.ts:5
  2 | function createInstance(params) {
  3 |     return new MatomoTracker(params);
  4 | }
> 5 | export default createInstance;
  6 | //# sourceMappingURL=instance.js.map
View compiled

I'd expect matomo-tracker not to throw errors.

TrackEvents on DOM changes using a MutationObserver

Problem:
We have a project using React and Elm. The enableLinkTracking function for React just works nice.
But for ELM (external) Javascript this doesn't work out of the Box.
Reviewing the MatomoTracker Code I just found the trackEvents() Method that is querying the DOM for data-matomo-event attributes.
However, for a reactive App we can not make use of this function as the DOM is not static.
But we like the approach to simply add a custom attribute to enable event clicking.

Solution:
To support custom attributes (data-matomo-event) on a frequently changing DOM, I think using a
MutationObserver would be a good solution dynamically add a Click-eventHandler on elements featuring a data-matomo-event attribute.

What do you think?
Are there alternatives I've missed?

can't set custom heartBeat value in seconds

It is mentioned in docs that we can use heartBeat: { active: true, seconds: 10 } to set custom time. But this line always returns default value 15:

if (!heartBeat || (heartBeat && heartBeat.active)) {
      this.enableHeartBeatTimer(15 || (heartBeat && heartBeat.seconds))
    }

Is it possible to replace this with

if (!heartBeat || (heartBeat && heartBeat.active)) {
      this.enableHeartBeatTimer((heartBeat && heartBeat.seconds) || 15)
    }

to make it work as expected?

Use functions for getting information

Is your feature request related to a problem? Please describe.
A Yes I want to fetch user's visitorId . It is not possible every visitor on my website is logged in. If the user is logged in then I am able to set the userId on initialization. But I want to get the visitorId of the current user. This can be achieved by passing a function as described in the documentation.

var visitor_id;
_paq.push([ function() { visitor_id = this.getVisitorId(); }]); 

But I didn't find a way to do that with the @datapunk/matomo-tracker-react

So I am requesting a feature to add passing functions to the Configuration of the Tracker Object (as mentioned on the documentation)

Describe the solution you'd like
A Be able to pass functions or getting visitorId directly

Describe alternatives you've considered
A I found out this plugin. I haven't tried any alternative methods that have found information here.

Additional context
I haven't worked with the javascript tracker by matomo I thought this plugin has all features.
I want to fetch the visitorId to track the user's behavior (page he visits, time spent on the website, etc). Then based on the data we will recommend articles that the user will like to read.

Resources
https://developer.matomo.org/api-reference/tracking-javascript
https://developer.matomo.org/guides/tracking-javascript-guide

Package Used
https://github.com/Amsterdam/matomo-tracker/tree/master/packages/react

Multiple Click Event listeners

Describe the bug

When you initiate the createInstance with the option as per documentation:
enableLinkTracking: false, // Important!

A new link tracking event listener is created. This lead thought the React Router Switch statement to generate 2 or more event listeners for outbound clicks. One for the instantiate and another one when the the component will load.

Added the linkTracking: false, // optional, default value: true still will create the same result. The issue is the following:
I see the issue be this line from the matomo-tracker (\src\MatomoTracker.ts):
` measure outbound links and downloads
// // might not work accurately on SPAs because new links (dom elements) are created dynamically without a server-side page reload.
this.enableLinkTracking(linkTracking)

[...]
static enableLinkTracking(active: boolean) {
window._paq.push(['enableLinkTracking', active])
}`

Searching on the Matomo documentation didn't find any instance of the use of the
window._paq.push(['enableLinkTracking', active])
More info: Disabling Download & Outlink tracking

To Reproduce
Steps to reproduce the behavior:

  1. Use the createInstance as per documentation
  2. Load another component after the initial load
  3. Run the const { enableLinkTracking } = useMatomo()
  4. Monitor that the link inside the loaded component will trigger one call but the initial components for example (header/footer links) will trigger 2!

Expected behavior
Depending on the parameters will have the option to disable the link tracking on the initial load

Desktop (please complete the following information):
Working with the latest version of the module: "@datapunt/matomo-tracker-react": "^0.1.5",

  • OS: [Windows]
  • Browser [ALL]

Additional context
Testing a React CRA project with everything updated
Adding the check to see if this is selected will resolve the issue:
if(linkTracking){ this.enableLinkTracking(linkTracking); }

Make tracking call to real noop

Describe the bug
In the current implementation, all calls pushes still to window._paq even if the tracker is disabled.

To Reproduce
Steps to reproduce the behavior:

  1. Create a instance of a tracker and set the disabled flag to true
  2. Use pushInstruction() for instance one or multiple times
  3. Inspect the window._paq

Expected behavior
The array should still be empty.

Missing ecommerce getter

Is your feature request related to a problem? Please describe.
Unfortunately the matomo javascript doesn't support promises or callbacks for the ecommerce actions.
(Further information: matomo-org/matomo#17756)

Since I need to wait until the order has been tracked, I'm trying to build a workaround by waiting until the untracked cart items are cleared (which occurs after successful order tracking)
However the problem is that this matomo-tracker doesn't provide the getter getEcommerceItems which is listed in the docs.

Describe the solution you'd like
I'd like the integration to provide the missing method getEcommerceItems

Describe alternatives you've considered
An alternative would be to do a PR in the matomo repo to add a callback in the trackOrder part.
However since this integration doesn't support everything that is listed in the docs, I'd start here.

According to TypeScript, siteId is a required property for the createInstance config parameter

Describe the bug
According to TypeScript, siteId is a required property for the config parameter in createInstance while, according to the docs, siteId is optional (whose default value is 1). Given the contradiction, either the TypeScript or the docs are incorrect.

To Reproduce
Steps to reproduce the behavior:

  1. Call createInstance with { urlBase: 'https://LINK.TO.DOMAIN' }
  2. See a TypeScript error explaining siteId is required
  3. See the Usage section of the React docs and notice siteId is said to be optional
  4. Be confused 🤔

Expected behavior
TypeScript and the docs live in harmony.

Screenshots
Screen Shot 2020-09-01 at 12 04 59 AM

Desktop (please complete the following information):

  • Version: 0.2.0

Support react native or remove the keyword from the package.json

Is your feature request related to a problem? Please describe.
Just spent half an hour adding your module just to find out it requires a global document. So no react native support even though the package.json specifies "react native" as a keyword.

Describe the solution you'd like
Either support react native, add documentation on how to get it running on RN or remove the keyword in package.json.

Describe alternatives you've considered

  • see above -

Thanks :-)

Globally enable / disable tracking after initialization within App

Is your feature request related to a problem? Please describe.
In the context of the EU Cookie Directive, tracking is only permitted with the consent of the website visitor.
In a cookie dialog, the visitor agrees or refuses to the setting of cookies. Matomo tracking can only be activated with consent.

Describe the solution you'd like
After first initialization of Matomo in index.tsx (as wrapper around die App) there shoud be a way to disable / enable Matomo tracking from anywhere within the app.

Something like

const { disableTracking } = useMatomo();

Describe alternatives you've considered
Enabling / Disabling all tracking-events manually in a component, based on a flag.

Additional context

Custom Dimensions didnt refresh on React

Context
I have created a HOC (higher-order component) to decorate the component pages of an application I'm working on, but I've faced some problems with custom dimensions.
In that HOC is where I use the hook to extract the trackPageView and trackEvent, and those are made available in the decorated component as props.

Here goes the problem: when I track an action with custom dimensions if I go to a different page, and I track the visit of that page, it keeps the custom dimensions, even if I don't send any.

Expected behavior
If I don't send any custom dimensions, they get cleared per request.

Desktop (please complete the following information):

  • OS: Windows 10
  • Browser: Chrome
  • 88

Missing callback support

The more I use matomo, the more missing features I find in this integration (sorry for that 😄 )

Since I must track some events before redirecting the use to another website, it's crucial to wait for matomo to be done with the tracking request. Matomo supports a callback param for this case
https://github.com/matomo-org/matomo/blob/fa66bc580852c2b098ba5ea7f7ba57048f258714/js/piwik.js#L6507

Unfortunately your integration doesn't care about this and doesn't provide a way to pass a callback.
That should be changed, precisely ALL additional data should be supported meaning

  • customTitle (trackPageView)
  • customData (trackPageView & trackEvent)
  • callback (trackPageView & trackEvent)

Use inside Class Components

I see the examples with how to use this package with hooks and function components. I try to do the same thing inside class based components and no luck. Is there a way to do this inside React Class Components? If not, what are the chances of this being included?

React matomo tracker does not track my React App on IE 11.

Describe the bug
React matomo tracker does not track my React App on IE 11.
it works well on other browsers.
Expected behavior
when I click anything on my React site using IE 11,I'm supposed to see the corresponding tracking record on my matomo site.
Desktop (please complete the following information):

  • OS: [WINDOWS 10]
  • Browser [IE 11]

Using `trackPageView` as described in docs results in a TypeScript error

Describe the bug
The following code (from the README):

import React from 'react'
import { useMatomo } from '@datapunt/matomo-tracker-react'

const MyPage = () => {
  const { trackPageView, trackEvent } = useMatomo()

  // Track page view
  React.useEffect(() => {
    trackPageView()
  }, [])

  const handleOnClick = () => {
    // Track click on button
    trackEvent({ category: 'sample-page', action: 'click-event' })
  }

  return (
    <button type="button" onClick={handleOnClick}>
      Click me
    </button>
  )
}

results in a TypeScript error.

To Reproduce
Steps to reproduce the behavior:

  1. Go to README
  2. Copy and paste the code described above into a component
  3. Note the TypeScript error

Expected behavior
TrackPageViewParams allows for undefined.

Screenshots
Screen Shot 2020-09-01 at 12 56 29 AM

Desktop (please complete the following information):

  • Version : 0.2.0

Multiple fake views

Hello there,

I have a little problem. Each time I go on a page, matomo logs 4 times the view. So 4 views on matomo for 1 view in real.
And for on other page it's often 2 times, and other pages no problem. It's depend of the page.

Code of Candidatures page (4 matomo views for 1 real view) :

const MatomoScript = ({renderFoo}) => {
	const {trackPageView} = useMatomo();
	return renderFoo({trackPageView});
};

class Candidatures extends React.Component {
render() {
		return (
			<Fragment>
				
				<MatomoScript renderFoo={({trackPageView}) => {
					trackPageView();
					return null;
					}
				}
				/>

And for login page (2 matomo views for 1 real view) :

const Connexion = ({ history }) => {
	
	const { trackPageView, trackEvent } = useMatomo();
	
	// Track page view
	trackPageView();

Index.js

const instance = createInstance({
	urlBase: "https://stats.level-up.education/",
	siteId: 2, // optional, default value: `1`
});

ReactDOM.render(
	<MatomoProvider value={instance}>
		<Root/>
	</MatomoProvider>,
	document.getElementById('root')
);

Use matomo tracker in class components

Is your feature request related to a problem? Please describe.
In our app there are still a lot of class components. How should I use The tracker in non-functional components which do not support hooks?

Describe the solution you'd like
A HOC or similar for the matomo wrapper

Describe alternatives you've considered
A documented workaround to use the current code in class components

trackEvent dependency triggers re-evaluation of hook all the time

Describe the bug
When trackEvent is added to a hook's dependencies, the hook is re-evaluated at each render

To Reproduce

  useEffect(() => {
    console.log('track event');
  }, [trackEvent]);

will log "track event" all the time

Expected behavior
trackEvent (as well as trackPageView) should only be set at first render, and console.log should only happen once.

Additional context
This current behavior means that when using trackEvent in a useCallback, adding trackEvent to dependencies (as should be done according to React Hooks best practices) as such:

  const handleClick = useCallback(() => {
    trackEvent({category: "my-page", value:"button-click"});
    doSomething();
  }, [trackEvent, doSomething]);

=> the "handleClick" callback will be reset all the time because of the trackEvent dependency, instead of just being evaluated when needed aka when a dependency changes.

trackPageView only records most recent page view

Hello,

I'm setting up Matomo with this library, and I've noticed that the default value of href´ in trackPageView` is the location object itself, which is passed by reference, so any time the location updates the, tracked history (as far as I can tell) changes with it.

The fix should be easy; change the default value of href to window.location.href in MatomoTracker.ts:135

Refactor export of type definitions

Right now we are exporting the types that are used from the root of the library as export { types }, meaning that you can import them and use them as follows:

import { types } from '@datapunt/matomo-tracker-js'

const options: types.UserOptions = {
  id: 1
}

From the perspective of shipping the types this makes very little sense, it also creates empty import statements which result in undefined values being exported in some bundlers.

This will have to be changed so the types are directly exported from the root package as follows:

export * from './types'

Which will make it possible to import these types directly:

import { UserOptions } from '@datapunt/matomo-tracker-js'

const options: UserOptions = {
  id: 1
}

React peer dependencies

Hello,
Thanks for the effort with these very fresh packages!

I just installed in on my react app and faced problems, that the react dependencies are not peerDependencies/devDependencies. Therefore it installed a second react version since I used react 16.8.6.

Unfortunatly I have only been able to develop locally by changing a lot of the lerna things (I have no experience with lerna unfortunately). Therefore I was not able yet to provide a PR.

Best regards,
Fabian.

Review imports to make proper use of /es or /lib folders

Describe the bug
On EI11, all javascript files have to be converted to ES5 to work properly. The matomo team offers /es (in ES6) and /lib (in ES5) to match this need. However, in matomo-tracker-react/lib/instance.js, require("@datapunt/matomo-tracker-js") does not explicitly target the lib folder. As such, this import defaults to the /es, which make apps on EI11 crash.

I fixed this bug writing explicitly require("@datapunt/matomo-tracker-js/lib").

To Reproduce
I created a simple repo:
https://github.com/TestardR/matomo-EI11-bug

  1. yarn install
  2. yarn start
  3. Open EI11 and Firefox/Chrome to compare

Expected behavior
It should show the classic CRA landing page.

Screenshots
Screenshot 2020-10-16 at 13 24 23 (3)

SCRIPT1002: Syntax error. As you can see, it clearly points to ES6 javascript.
Screenshot 2020-10-16 at 13 27 53

Desktop (please complete the following information):

  • OS: macOS Catalina
  • Browser EI
  • Version 11

Why different param names?

This is mostly a question (might end up in an improvement though)

In the course of my previous PR #562 I've noticed the params are named different than in the official matomo docs https://developer.matomo.org/api-reference/tracking-javascript

For example the action trackEcommerceOrder where matomo calls the 2nd param grandTotal whereas your integration calls it orderRevenue https://github.com/Amsterdam/matomo-tracker/blob/master/packages/js/src/MatomoTracker.ts#L241

@chrisvanmook is there a particular reason for this discrepancy?
Has matomo changed those names?

If not I'd suggest to name it identically to the official docs to avoid any confusion and unnecessary mapping.

trackPageView useEffect is re-triggered all the time, following useEffect best practices

Describe the bug
trackPageView is re-triggered all the time, following useEffect best practices

To Reproduce

useEffect(() => {
    console.log('track page view');
    trackPageView();
}, [trackPageView]); // adding trackPageView dependency, according to React Hooks best practices

Visit the page once => triggers multiple "track page view" console.logs & matomo events

Expected behavior
Triggers 1 "track page view" console.log & matomo event for 1 visit

Additional context

  • React ^16.8.0
  • React-Router ^5.1.2
  • Matomo-Tracker-React ^0.2.1

urlBase and siteId is required even when disabled is true

Describe the bug

When creating a MatomoTracker, it raises an error if urlBase or siteId is empty value even when disabled is true.

To Reproduce

Run the following code.

import MatomoTracker from '@datapunt/matomo-tracker-js'

const tracker = new MatomoTracker({
  urlBase: '',
  siteId: 1,
  disabled: true,
})

Expected behavior

We can create MatomoTracker without an error with empty urlBase or siteId when disabled is true.

Multiple tracker objects

Is your feature request related to a problem? Please describe.
Unable to have two instances of Matomo for the same code base, example, if I have a SPA and a Microfrontend, even though, they are different projects, they share the same URL and bundle, but if both requires different implementation for Matomo, with siteID or even baseURL, it's not possible since the first createInstance conflicts and overwrites the other and there's no way to distinguish posterior calls to trackEvent, trackPageView, pushInstruction and etc.

Describe the solution you'd like
Direct references or calls to either "getAsyncTracker" or/and "addTracker", according to Matomo guide for multiple instances/trackers: https://developer.matomo.org/guides/tracking-javascript-guide#customise-one-of-the-tracker-object-instances

Integration with React Typescript

Is there a @types package available for this? I am using React with Typescript for my project. It is failing during build because of the absence of .ts/.tsx files for this plugin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.