@certible/use-matomo

中文文档
1.3.0发布于 2026/11/09MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 9299

A typed framework agnostic wrapper for Matomo js including SPA tracking.

原始使用文档
文档目录17 节
  1. Installation
  2. Usage
  3. vue.js
  4. Configuration Options
  5. Required Options
  6. Optional Options
  7. Initial Page View
  8. Example with All Options
  9. API Methods
  10. trackEvent(category, action, name?, value?)
  11. trackPageView(url?, props?)
  12. setUserId(userId)
  13. destroy()
  14. ready
  15. push(args)
  16. License
  17. About

use-matomo

A typed framework agnostic wrapper for Matomo js including SPA tracking.

Installation

# NPM
npm install @certible/use-matomo
# PNPM
pnpm add @certible/use-matomo

Usage

import { initMatomo } from '@certible/use-matomo';

const matomo = initMatomo({
  host: 'https://your-matomo-instance.com',
  siteId: 1,
  // trackRouter: true, automatically tracks SPA page changes via history tracking
});

// Manually track router changes
// router.afterEach((to, from) => {
//   matomo.trackPageView(to.path, opts);
// });

// Track an event
matomo.trackEvent('Category', 'Action', 'Name', 1);

vue.js

import { initMatomo } from '@certible/use-matomo';
import { createApp } from 'vue';
import App from './App.vue';

const app = createApp(App);

const matomo = initMatomo({
  host: 'https://your-matomo-instance.com',
  siteId: 1,
  // trackRouter: true, automatically tracks SPA page changes via history tracking
}));

app.provide<MatomoTracker>('matomo', matomo);
// In your components, you can access Matomo like this:
import { inject } from 'vue';

const matomo = inject<MatomoTracker>('matomo');

Quasar

// quasar boot file: src/boot/matomo.js
import { defineBoot } from '#q-app/wrappers';
import { initMatomo } from '@certible/use-matomo';


export default defineBoot(({ app }) => {
  const matomo = initMatomo({
    host: 'https://your-matomo-instance.com',
    siteId: 1,
    // trackRouter: true, automatically tracks SPA page changes via history tracking
  });

  app.provide('matomo', matomo);
});

Configuration Options

The initMatomo function accepts a configuration object with the following options:

Required Options

OptionTypeDescription
hoststringThe URL of your Matomo instance (e.g., https://your-matomo-instance.com)
siteIdnumber | stringThe site ID in your Matomo instance

Optional Options

OptionTypeDefaultDescription
trackerFileNamestring'matomo'The filename of the tracker script and endpoint
trackerUrlstring''Custom tracker endpoint URL. If empty, uses {host}/{trackerFileName}.php
trackerScriptUrlstring''Custom tracker script URL. If empty, uses {host}/{trackerFileName}.js
trackerScriptDisablebooleanfalseDisable automatic loading of the tracker script (useful if already loaded)
enableLinkTrackingbooleantrueEnable automatic tracking of outbound links and downloads
requireConsentbooleanfalseRequire user consent before tracking (GDPR compliance)
userIdstring''Set a user ID for tracking across sessions
disableCookiesbooleanfalsewindow._paq.push(['disableCookies'])
requireCookieConsentbooleanfalsewindow._paq.push(['requireCookieConsent'])
enableHeartBeatTimerbooleanfalsewindow._paq.push(['enableHeartBeatTimer', options.heartBeatTimerInterval])
heartBeatTimerIntervalnumber15Heartbeat timer interval in seconds
cookieDomainstring''Set the cookie domain for cross-subdomain tracking, window._paq.push(['setCookieDomain', options.cookieDomain])
domainsstring[][]List of domains to track as internal (for cross-domain tracking), window._paq.push(['setDomains', options.domains])
crossOrigin'anonymous' | 'use-credentials'undefinedCross-origin attribute for the tracker script
preInitActionsMatomoCommand[][]Array of Matomo commands to execute before initialization
trackRouterbooleanfalseAutomatically track SPA page changes via history API monitoring
trackInitialViewbooleantrueTrack the initial page view during initialization. Set to false to call trackPageView() yourself, e.g. after your app sets the route title

Initial Page View

initMatomo queues the initial page view immediately, so an early navigation cannot replace the entry URL. When the tracker script processes the queue, it reads document.title again, as long as the URL did not change. Thus a title that your app sets while the tracker script loads is used.

If your app sets the title later, set trackInitialView: false and track the initial page view yourself:

const matomo = initMatomo({
  host: 'https://analytics.example.com',
  siteId: 1,
  trackInitialView: false,
});

// After the first route resolved and set the title
matomo.trackPageView();

Link tracking (enableLinkTracking) is queued with each trackPageView() call. With trackInitialView: false, it starts with your first call.

Example with All Options

const matomo = initMatomo({
  host: 'https://analytics.example.com',
  siteId: 1,
  trackerFileName: 'piwik', // For older Matomo instances
  enableLinkTracking: true,
  requireConsent: true, // GDPR compliance
  disableCookies: false,
  enableHeartBeatTimer: true,
  heartBeatTimerInterval: 30,
  cookieDomain: '.example.com',
  domains: ['*.example.com', 'subdomain.example.com'],
  trackRouter: true, // Automatic SPA tracking
  preInitActions: [
    ['setCustomDimension', 1, 'Premium User']
  ]
});

API Methods

Once initialized, the Matomo tracker returns an object with the following methods:

trackEvent(category, action, name?, value?)

Tracks a custom event.

Parameters:

  • category (string): The category of the event
  • action (string): The action of the event
  • name (string, optional): The name of the event
  • value (number, optional): The value of the event

Example:

// Track a button click
matomo.trackEvent('Navigation', 'Click', 'Header Logo');

// Track with a value
matomo.trackEvent('Purchase', 'Complete', 'Premium Plan', 99.99);

trackPageView(url?, props?)

Tracks a page view in a single-page application.

Parameters:

  • url (string, optional): The URL of the page to track. Defaults to window.location.href
  • props (object, optional): Additional properties for the page view
    • deleteCustomVariables (boolean): Whether to delete custom variables. Default: true
    • documentTitle (string): Custom document title. Default: document.title

Example:

// Track current page
matomo.trackPageView();

// Track specific URL
matomo.trackPageView('/dashboard');

// Track with custom title
matomo.trackPageView('/profile', { 
  documentTitle: 'User Profile - MyApp' 
});

setUserId(userId)

Sets or resets the user ID for tracking across sessions.

Parameters:

  • userId (string | null): The user ID to set, or null to reset

Example:

// Set user ID
matomo.setUserId('user123');

// Reset user ID
matomo.setUserId(null);

destroy()

Removes router tracking listeners and restores patched history methods.

Use this when trackRouter is enabled and your app tears down the tracker, for example during hot module replacement or tests.

Vite HMR example:

const matomo = initMatomo({
  host: 'https://analytics.example.com',
  siteId: 1,
  trackRouter: true,
});

if (import.meta.hot) {
  import.meta.hot.dispose(() => {
    matomo.destroy();
  });
}

ready

Promise that resolves after the tracker script loads. The initial page view (if trackInitialView is true) is queued during initialization. It rejects when the script fails to load.

Example:

await matomo.ready;

push(args)

Pushes any instruction directly to the Matomo tracker. This allows you to use any Matomo tracking method not explicitly exposed by this wrapper.

Parameters:

  • args (array): Array of arguments to pass to Matomo

Example:

// Set custom dimension
matomo.push(['setCustomDimension', 1, 'Premium User']);

// Track site search
matomo.push(['trackSiteSearch', 'keyword', 'category', 5]);

// Set custom variable
matomo.push(['setCustomVariable', 1, 'UserType', 'Premium', 'visit']);

For a complete list of available Matomo tracking methods, see the Matomo JavaScript Tracking Guide.

License

This project is licensed under the MIT License.

About

This package is developed and maintained by Certible.

版本与发布记录

@certible/use-matomo 共发布 6 个版本,首次发布于 2025/08/11;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.3.0latest2026/11/09今天
1.2.22026/11/053 天前
1.2.12026/07/163 个月前
1.2.02026/05/275 个月前
1.1.02025/08/111.2 年前
1.0.02025/08/111.2 年前

关于 @certible/use-matomo 的常见问题

@certible/use-matomo 是什么?

A typed framework agnostic wrapper for Matomo js including SPA tracking.

如何安装 @certible/use-matomo?

在项目目录运行 npm install @certible/use-matomo,或使用 pnpm add / yarn add / bun add。

@certible/use-matomo 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@certible/use-matomo 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@certible/use-matomo 可以商用吗?

@certible/use-matomo 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@certible/use-matomo 的下载量有多少?

根据 npm 官方下载统计,@certible/use-matomo 在 2026/10/10 – 2026/11/08 这 30 天内被下载 9,299 次,日均约 310 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@certible/use-matomo 还在维护吗?

最新版本 1.3.0 发布于 2026/11/09(今天);至今共发布 6 个版本,其中过去 12 个月发布了 4 个;首次发布于 2025/08/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。