### Install Node.js version Source: https://github.com/yandex/metrica-tag/blob/main/README.md Uses nvm to install the required Node.js version for the project. ```bash nvm install ``` -------------------------------- ### Install dependencies Source: https://github.com/yandex/metrica-tag/blob/main/README.md Installs project dependencies using npm. ```bash npm ci ``` -------------------------------- ### Example server response structure Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/transport.md Example of a JSON response containing counter settings. ```json // Server might return: { 'settings': { 'enable_goal': true, 'enable_clickmap': false } } // Middleware processes and counter applies settings ``` -------------------------------- ### MetrikaCounter Initialization Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Examples showing basic initialization using an object configuration or direct positional arguments. ```javascript // Basic initialization new Ya.Metrica({ id: 123456, params: { custom_param: 'value' }, sendTitle: true, trackHash: true }); // Or using direct call with positional arguments Ya.Metrica( 123456, { custom_param: 'value' }, 0, // counterType false // counterDefer ); ``` -------------------------------- ### Initialize Custom Constructor Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Example of instantiating the tracker using the custom name defined during build. ```javascript new Ya.MyTracker({ id: 123456 }); ``` -------------------------------- ### Initialize Minimal Metrica Counter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Basic setup requiring only the counter ID. ```javascript // Basic initialization with required ID only new Ya.Metrica({ id: 123456 }); ``` -------------------------------- ### Build Metrica Script Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Commands to install dependencies and build the project for custom feature usage. ```bash npm install npm run build ``` -------------------------------- ### startsWith(str, prefix) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Checks if a string starts with a specified prefix. ```APIDOC ## startsWith(str, prefix) ### Description Checks if string starts with prefix (polyfill-compatible). ### Signature `function startsWith(str: string, prefix: string): boolean;` ``` -------------------------------- ### Modify Build-Time Features Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Example of a feature definition in features.json and the command to rebuild the project. ```json { "code": "GOAL_FEATURE", "path": "goal", "desc": "Goal tracking provider", "disabled": false } ``` ```bash npm run features ``` -------------------------------- ### Get Location Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Extracts the location object from the provided window context. ```typescript function getLocation(ctx: Window): Location; ``` -------------------------------- ### Get Browser Info Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Retrieves browser and page metadata, optionally accepting overrides. ```typescript function browserInfo( overrides?: Record ): BrowserInfo; ``` -------------------------------- ### Get object entries Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Returns an array of [key, value] pairs from the provided object. ```typescript function entries>( obj: T ): Array<[keyof T, T[keyof T]]>; ``` -------------------------------- ### Build the project Source: https://github.com/yandex/metrica-tag/blob/main/README.md Compiles the project into the _build/public/watch.js file. ```bash npm run build ``` ```bash npm run build:raw ``` -------------------------------- ### getMs(ctx) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Gets current time in milliseconds. ```APIDOC ## getMs(ctx) ### Description Gets current time in milliseconds. ### Signature `function getMs(ctx: Window): number;` ### Returns Milliseconds since epoch ``` -------------------------------- ### Development Workflow Commands Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Standard commands for linting and setting up development hooks. ```bash npm run lint ``` ```bash npm run setup-hooks ``` -------------------------------- ### Get Unique Identifier Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Generates or retrieves a 128-bit unique identifier string. ```typescript function getUID(): string; ``` -------------------------------- ### Integrate with Tag Manager Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Use the defer option to delay initialization and trigger events manually based on user interaction. ```html ``` -------------------------------- ### Implement Simple Website Tracking Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Configure basic tracking features like page titles, hash-based navigation, and link tracking. ```html ``` -------------------------------- ### Get current time in milliseconds Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Returns the current time in milliseconds since the epoch. ```typescript function getMs(ctx: Window): number; ``` -------------------------------- ### Initialize Basic Metrica Script Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Include this script before the closing body tag to initialize the counter. ```html ``` -------------------------------- ### Initialize Full Featured Metrica Counter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Comprehensive configuration including custom parameters, user attributes, and tracking flags. ```javascript new Ya.Metrica({ id: 123456, type: 0, params: { project: 'website-v2', environment: 'production' }, userParams: { customer_id: 'cust_12345', account_level: 'premium' }, sendTitle: true, trackHash: true, trackLinks: true, defer: false, noCookie: false, ldc: 'example.com', triggerEvent: true }); ``` -------------------------------- ### Build Commands Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Commands for generating production or development builds and configuring features. ```bash npm run build ``` ```bash npm run build:raw ``` ```bash # Edit features.json, then: npm run features npm run build ``` ```bash CONSTRUCT_NAME=MyTracker npm run build ``` -------------------------------- ### Get nested property by path Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Retrieves a nested property from an object using dot notation. ```typescript function getPath(obj: any, path: string): any; ``` ```typescript const value = getPath(window, 'Ya.Metrica'); ``` -------------------------------- ### Verify Counter Initialization Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Use these commands in the browser console to confirm the Metrica object and counters are correctly loaded. ```javascript // Verify counter exists console.log(window.Ya); console.log(window.Ya.Metrica); console.log(window.Ya.getCounters()); ``` -------------------------------- ### Check Initialization Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Verifies that the Yandex Metrica object and counters are correctly attached to the window object. ```javascript console.log(window.Ya); console.log(window.Ya.Metrica); console.log(window.Ya.getCounters()); ``` -------------------------------- ### GET/POST https://mc.yandex.ru/watch/[COUNTER_ID] Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Sends a pageview hit to the Yandex Metrica counter. Supports both GET and POST methods. ```APIDOC ## GET/POST https://mc.yandex.ru/watch/[COUNTER_ID] ### Description Sends a pageview hit to the Yandex Metrica counter. The API supports two protocol variants: Standard (mc.yandex.ru) and Collect (collect.yandex.ru). ### Method GET/POST ### Endpoint https://mc.yandex.ru/watch/[COUNTER_ID] ### Parameters #### Path Parameters - **COUNTER_ID** (string) - Required - The unique identifier for the counter. #### Query Parameters - **tid** (string) - Optional - ID parameter. - **page-url** (string) - Optional - The URL of the page. - **page-ref** (string) - Optional - The referrer URL. - **pv** (integer) - Optional - Pageview flag (set to 1). - **t** (string) - Optional - Page title. - **s** (string) - Optional - Screen resolution. - **uid** (string) - Optional - User ID. - **dl** (string) - Optional - Page URL (Collect variant). - **dr** (string) - Optional - Referrer URL (Collect variant). ``` -------------------------------- ### Initialize Testing/Staging Metrica Counter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Configuration for staging environments, disabling cookie persistence to avoid polluting production data. ```javascript new Ya.Metrica({ id: 123456, params: { environment: 'staging', internal_user: true }, noCookie: true // Don't persist IDs in staging }); ``` -------------------------------- ### Configure Image Beacon Transport Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/transport.md Defines the configuration object for Image Beacon requests, which are limited to GET requests with query string parameters. ```typescript { verb: 'GET', rQuery: { tid: '123456', ... } } ``` -------------------------------- ### Check Browser Capabilities Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Initializes a counter instance to verify client ID retrieval. ```javascript const counter = new Ya.Metrica({ id: 123456 }); const clientId = counter.getClientID(); console.log('User ID:', clientId); ``` -------------------------------- ### Invoke Common Counter Methods Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md List of available instance methods for tracking goals, user parameters, and managing counter state. ```javascript counter.reachGoal(goalName, params?, callback?, context?); counter.params(name, value); counter.userParams(params); counter.getClientID(); counter.setUserID(userId); counter.notBounce(options?); counter.accurateTrackBounce(time?); counter.file(url); counter.extLink(url); counter.trackLinks(config); counter.addFileExtension(ext); counter.destruct(); ``` -------------------------------- ### Implement and Register Custom Middleware Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/transport.md Shows the structure of a custom middleware implementation and how to register it to a provider. ```typescript // Custom middleware implementation const myMiddleware: MiddlewareGetter = (ctx, options) => ({ beforeRequest: (senderInfo, next) => { senderInfo.urlParams = senderInfo.urlParams || {}; senderInfo.urlParams['my_param'] = 'value'; next(); }, afterRequest: (senderInfo, next) => { console.log('Request sent with status:', senderInfo.responseInfo); next(); } }); // Register in provider providerMiddlewareList[MY_PROVIDER] = [myMiddleware]; ``` -------------------------------- ### Integrate E-Commerce Tracking Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Set up session parameters, user identification, and purchase goal tracking. ```html ``` -------------------------------- ### Verify Initialization Before Use Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Ensure the counter is properly initialized before calling methods to avoid runtime errors. ```javascript // DON'T DO THIS if (window.Ya && window.Ya.Metrica) { // This might fail if defer:true window.Ya.Metrica(...).reachGoal('test'); } ``` ```javascript // Store reference and check it const counter = new Ya.Metrica({ id: 123456 }); if (counter) { counter.reachGoal('test'); } // Or wrap in try-catch try { counter.reachGoal('test'); } catch (e) { console.error('Counter not ready', e); } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Executes the unit test suite using the configured test runner. ```bash npm run test:unit ``` -------------------------------- ### Initialize E-Commerce Metrica Counter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Configuration tailored for e-commerce tracking, including direct campaign IDs and store-specific parameters. ```javascript new Ya.Metrica({ id: 123456, params: { store: 'main', currency: 'USD' }, userParams: { customer_id: user.id, vip_status: user.isVIP }, trackHash: true, trackLinks: true, directCampaign: 987654 }); ``` -------------------------------- ### Counter Initialization Options Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/00-START-HERE.md Configuration object properties used when instantiating the Ya.Metrica object. ```javascript new Ya.Metrica({ id: NUMBER, // Required params: {}, // Session parameters userParams: {}, // User information sendTitle: BOOLEAN, // Include document title trackHash: BOOLEAN, // Track URL changes trackLinks: BOOLEAN, // Auto-track clicks // ... 10+ more options }); ``` -------------------------------- ### Initialize with hash tracking Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Enable URL hash tracking during counter initialization to support single-page application navigation. ```javascript new Ya.Metrica({ id: 123456, trackHash: true // Track SPA navigation }); // Later navigation triggers new hits // /page -> /page#section1 -> /page#section2 ``` -------------------------------- ### Compose and Execute Middleware Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/transport.md Demonstrates how to combine middleware functions and execute them before and after a transport request. ```typescript const combinedMiddleware = [ prepareUrlMiddleware, paramsMiddleware, userParamsMiddleware, senderWatchInfoMiddleware, csrfMiddleware, pageTitle Middleware, prerenderMiddleware, // ... others ]; // Execute before sending request await combineMiddlewares(combinedMiddleware, senderInfo, before=true); // Send request const response = await transport.send(url, options); // Execute after response await combineMiddlewares(combinedMiddleware, senderInfo, before=false); ``` -------------------------------- ### Check string prefix with startsWith Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Determines if a string begins with a specified prefix, providing a polyfill-compatible implementation. ```typescript function startsWith(str: string, prefix: string): boolean; ``` -------------------------------- ### Defining a Feature Flag Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Register a new provider in the features.json file to enable it within the system. ```json { "code": "MY_FEATURE", "path": "myProvider", "desc": "My custom provider", "disabled": false, "weight": 100 } ``` -------------------------------- ### Implement Environment-Specific Configuration Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Dynamically adjust counter settings based on the current environment (production vs. development). ```javascript const isProduction = window.location.hostname.includes('example.com'); const isDevelopment = window.location.hostname === 'localhost'; const counterConfig = { id: 123456, params: { environment: isProduction ? 'production' : 'development', debug: isDevelopment }, // In development: don't persist cookies noCookie: isDevelopment, // In production: track everything trackHash: isProduction, trackLinks: isProduction }; const counter = new Ya.Metrica(counterConfig); ``` -------------------------------- ### Project Directory Structure Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/modules.md Visual representation of the project file hierarchy. ```text metrica-tag/ ├── src/ │ ├── api/ # API constants (endpoints, parameters) │ ├── middleware/ # Request processing middleware │ ├── providers/ # Feature providers │ ├── sender/ # Request composition and sending │ ├── transport/ # HTTP transport implementations │ ├── utils/ # Utility functions and helpers │ ├── inject/ # Build-time dependency injection │ ├── config.ts # Global configuration │ ├── const.ts # Global constants │ ├── index.ts # Main entry point │ ├── types.ts # Global type definitions │ └── providersEntrypoint.ts # Provider initialization ├── features.json # Feature flags configuration └── rolldown.config.ts # Build configuration ``` -------------------------------- ### Implement Consent Management Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Manage tracking initialization based on user consent status for cookies and data collection. ```javascript // GDPR/CCPA compliant class AnalyticsManager { constructor() { this.counter = null; this.consentGiven = false; } initialize() { // Check for existing consent const consent = this.checkConsent(); if (consent) { this.enableTracking(); } else { // Wait for user consent this.onConsentChange(() => this.enableTracking()); } } enableTracking() { if (this.counter) return; this.counter = new Ya.Metrica({ id: 123456, noCookie: !this.consentForCookies(), params: { consent_given: true } }); this.consentGiven = true; } trackEvent(name, data) { if (this.consentGiven && this.counter) { this.counter.reachGoal(name, data); } } checkConsent() { // Your consent detection logic return localStorage.getItem('analytics_consent') === 'true'; } onConsentChange(callback) { // Listen for consent updates window.addEventListener('analytics:consent', callback); } consentForCookies() { // Check if user consents to persistent storage return localStorage.getItem('cookies_consent') === 'true'; } } const analytics = new AnalyticsManager(); analytics.initialize(); ``` -------------------------------- ### Rebuild Project Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Execute build commands after modifying feature configurations. ```bash npm run features npm run build ``` -------------------------------- ### Ya.Metrica Initialization Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Initializes a new Yandex Metrica counter instance with the required counter ID and optional configuration settings. ```APIDOC ## Ya.Metrica Constructor ### Description Initializes the Yandex Metrica counter. ### Signature `new Ya.Metrica(options)` ### Parameters - **options** (Object) - Required - **id** (Number) - Required: The counter ID. - **params** (Object) - Optional: Session parameters. - **userParams** (Object) - Optional: User information. - **sendTitle** (Boolean) - Optional: Whether to send page title. - **trackHash** (Boolean) - Optional: Whether to track hash changes. - **trackLinks** (Boolean) - Optional: Whether to track clicks on links. ``` -------------------------------- ### Configure CSP with Nonce Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Use a nonce attribute on the script tag to comply with strict Content Security Policy requirements. ```html ``` -------------------------------- ### Integrate A/B Testing in JavaScript Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Use client IDs to assign users to experiment groups and track variant-specific goals and parameters. ```javascript const counter = new Ya.Metrica({ id: 123456 }); // Get consistent user ID for A/B grouping const userId = counter.getClientID(); const userGroup = hashUserId(userId) % 2; // Group A (0) or B (1) // Track experiment variant counter.userParams({ experiment_id: 'button_color_v1', variant: userGroup === 0 ? 'control' : 'treatment', user_hash: userId }); // Track variant-specific goals counter.params({ variant: userGroup === 0 ? 'control' : 'treatment' }); // Later: track conversion counter.reachGoal('conversion', { variant: userGroup === 0 ? 'control' : 'treatment', revenue: amount }); function hashUserId(id) { let hash = 0; for (let i = 0; i < id.length; i++) { hash = ((hash << 5) - hash) + id.charCodeAt(i); hash = hash & hash; // 32-bit integer } return Math.abs(hash); } ``` -------------------------------- ### Define a new feature in features.json Source: https://github.com/yandex/metrica-tag/blob/main/README.md Add a new feature entry to the features.json configuration file to register a provider. ```json { "code": "SOME_NEW_FEATURE", // The name of generated variable to be used in code. "path": "someNewProvider", // The path to the folder within src/providers with the module that defined the new provider. "desc": "Any meaningful description goes here", "disabled": true, // Set only if you want to exclude a feature from build. "exp": true, // A semantic attribute indicating an experimental feature. Doesn't affect the build process. "weight": 1000, /* A feature weight; defaults to 0 if not specified. Used for sorting features within feature initialization code in ascending order (the lower the weight, the earlier the provider initializes). Used for predictable initialization order. For example see the STACK_PROXY_FEATURE that must be initialized in the very end. */ }, ``` -------------------------------- ### Integrate Metrica in React SPA Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Initialize the counter on mount and track route changes using React hooks. ```javascript // React example import React, { useEffect } from 'react'; function App() { const [counter, setCounter] = React.useState(null); useEffect(() => { // Initialize on mount const metrika = new window.Ya.Metrica({ id: 123456, defer: false, // Auto-send initial hit trackHash: true }); setCounter(metrika); }, []); useEffect(() => { // Track SPA page changes if (counter) { // Using accurateTrackBounce for engagement counter.accurateTrackBounce(30000); } }, [counter, location]); return ( // Your app ); } // Track user actions function trackPurchase(amount) { window.Ya.Metrica.counters[0]?.reachGoal('purchase', { amount }); } ``` -------------------------------- ### Implementing a New Provider Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Define a new provider by creating an index file that registers a function based on feature flags and extends the CounterObject interface. ```typescript // src/providers/myProvider/index.ts import { flags } from '@inject'; import { providersSync } from 'src/providersEntrypoint'; declare module 'src/utils/counter/type' { interface CounterObject { myMethod?: (arg: string) => CounterObject; } } export const initProvider = () => { if (flags.MY_FEATURE) { providersSync.push(myProviderFn); } }; // Provider function const myProviderFn = (ctx: Window, counterOptions: CounterOptions) => { return { myMethod: (arg: string) => { // Method implementation return this; // Return counter for chaining } }; }; ``` -------------------------------- ### Static Methods Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Static methods available on the Ya.Metrica class. ```APIDOC ## Ya.Metrica.getCounters() ### Description Returns a list of all initialized counters. ``` -------------------------------- ### Create Event Emitter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Initializes a pub/sub event emitter instance. ```typescript function createEventEmitter(): { on(event: string, fn: (data: T) => void): void; emit(event: string, data: T): void; off(event: string, fn?: (data: T) => void): void; }; ``` -------------------------------- ### select(ctx, selector) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Selects all elements matching selector. ```APIDOC ## select(ctx, selector) ### Description Selects all elements matching selector. ### Signature `function select(ctx: Window, selector: string): HTMLElement[];` ### Returns Array of matching elements ``` -------------------------------- ### MetrikaCounter Constructor Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Initializes a new Metrica tracking counter instance. The constructor accepts a counter ID and optional configuration parameters to track user activity and goals. ```APIDOC ## MetrikaCounter Constructor ### Description The MetrikaCounter is the main constructor function that initializes a Metrica tracking counter on a web page. It collects analytics data and exposes methods for tracking goals and user actions. ### Signature `MetrikaCounter(counterId: number, counterParams?: Record, counterType?: number, counterDefer?: boolean) => void` ### Parameters - **counterId** (number) - Required - Unique identifier for the counter - **counterParams** (Record) - Optional - Additional parameters to be sent with hits - **counterType** (number) - Optional - Counter type (0 for default, other values for advertising networks) - **counterDefer** (boolean) - Optional - If true, the initial pageview hit is deferred ### Example Usage ```javascript // Direct call with positional arguments Ya.Metrica( 123456, { custom_param: 'value' }, 0, false ); ``` ``` -------------------------------- ### Visualize Request Flow Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Diagram showing the lifecycle of a counter method call from invocation to completion. ```text Counter Method Call ↓ Method Decorator (error handling, chaining) ↓ Provider Handler (specific logic) ↓ Before-Request Middleware (modify parameters) ↓ Transport Selection (fetch/beacon/xhr/image) ↓ HTTP Request Sent ↓ Response Processing ↓ After-Request Middleware (process response) ↓ Complete ``` -------------------------------- ### Define CounterOptions Interface Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/types.md The primary configuration interface for initializing MetrikaCounter instances and provider functions. ```typescript interface CounterOptions { id: number; params?: Params; counterDefer?: boolean; ut?: boolean; counterType: CounterTypeInterface; userParams?: Record; ldc?: string; noCookie?: boolean; forceUrl?: string; forceReferrer?: string; triggerEvent?: boolean; sendTitle?: boolean; trackHash?: boolean; directCampaign?: number; trackLinks?: RawTrackLinkParams; } ``` -------------------------------- ### Initialize Deferred Metrica Counter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Used for Tag Manager scenarios where pageview tracking is triggered manually after initialization. ```javascript // Skip automatic pageview, send manually later new Ya.Metrica({ id: 123456, defer: true }); // Later, when ready to track: counter.reachGoal('page_loaded'); ``` -------------------------------- ### Add custom file extension Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Registers a new file extension to be tracked as a download. ```javascript counter.addFileExtension('epub'); ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Set the debug flag to true during initialization to enable console logging for troubleshooting. ```javascript const counter = new Ya.Metrica({ id: 123456, debug: true // Enables console logging }); ``` -------------------------------- ### getInstance(counterId) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Retrieves or creates a counter instance. ```APIDOC ## getInstance(counterId) ### Description Gets or creates counter instance from global registry. ### Signature `function getInstance(counterId: number): CounterObject;` ``` -------------------------------- ### Initialize the Yandex Metrica Counter Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/00-START-HERE.md Place this snippet before the closing tag to initialize the tracking counter. ```javascript ``` -------------------------------- ### ctxBindArgs(args) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Curried version of bindArgs for context binding. ```APIDOC ## ctxBindArgs(args) ### Description Curried version of bindArgs for context binding. ### Signature `function ctxBindArgs(args: any[]): (fn: T) => (...rest: any[]) => ReturnType;` ``` -------------------------------- ### Common Counter Methods Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Methods available on the counter instance for tracking goals, setting parameters, and managing user data. ```APIDOC ## Counter Methods ### reachGoal(goalName, params?, callback?, context?) Tracks a specific goal. ### params(name, value) Sets session parameters. ### userParams(params) Sets user-specific parameters. ### getClientID() Returns the client ID. ### setUserID(userId) Sets the user ID. ### notBounce(options?) Marks a visit as not a bounce. ### accurateTrackBounce(time?) Sets the time threshold for accurate bounce tracking. ### file(url) Tracks a file download. ### extLink(url) Tracks an external link click. ### trackLinks(config) Configures link tracking. ### addFileExtension(ext) Adds a file extension to the tracking list. ### destruct() Destroys the counter instance and cleans up listeners. ``` -------------------------------- ### Enable Console Logging Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Set the debug option to true during counter initialization to enable console logging. ```javascript new Ya.Metrica({ id: 123456, debug: true // Enable debug logging }); ``` -------------------------------- ### Click Tracking Provider Methods Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Methods for tracking file downloads, external link clicks, and configuring automatic link tracking. ```APIDOC ## counter.file(url) ### Description Tracks a file download event. ### Parameters - **url** (string) - Required - The URL of the file being downloaded. ## counter.extLink(url) ### Description Tracks a click on an external link. ### Parameters - **url** (string) - Required - The URL of the external link. ## counter.trackLinks(config) ### Description Enables automatic tracking of links. ### Parameters - **config** (boolean|string|object) - Required - Tracking configuration or CSS selector string. ## counter.addFileExtension(ext) ### Description Adds a custom file extension to the list of tracked file types. ### Parameters - **ext** (string) - Required - The file extension to add. ``` -------------------------------- ### Defer counter initialization Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Use this configuration to delay the initialization of the counter if it is not critical for the initial page load. ```javascript { defer: true } ``` -------------------------------- ### View Module Organization Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Directory structure of the source code repository. ```text src/ ├── index.ts ← Entry point, counter constructor ├── types.ts ← Global type definitions ├── config.ts ← Configuration values ├── const.ts ← Runtime constants ├── providersEntrypoint.ts ← Provider registry │ ├── api/ ← Backend communication constants ├── providers/ ← Feature implementations ├── middleware/ ← Request processing ├── sender/ ← Request composition ├── transport/ ← HTTP implementations └── utils/ ← Helper functions ``` -------------------------------- ### runAsync(ctx, fn, scope) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Schedules a function to run asynchronously. ```APIDOC ## runAsync(ctx, fn, scope) ### Description Schedules function to run asynchronously. ### Parameters - **ctx** (Window) - Required - Window object - **fn** (AnyFunc) - Required - Function to execute asynchronously - **scope** (string) - Required - Scope identifier for error logging ``` -------------------------------- ### Monitor Performance and Errors in JavaScript Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Implement performance tracking using the window.performance API and capture JavaScript errors and unhandled promise rejections. ```javascript const counter = new Ya.Metrica({ id: 123456, params: { tracking: 'performance' } }); // Measure custom metrics function reportPerformance() { const perfData = window.performance.timing; const pageLoadTime = perfData.loadEventEnd - perfData.navigationStart; counter.reachGoal('page_load_time', { total_time: pageLoadTime, dom_ready: perfData.domContentLoadedEventEnd - perfData.navigationStart, first_paint: perfData.responseEnd - perfData.navigationStart }); } // Report when page is fully loaded if (document.readyState === 'complete') { reportPerformance(); } else { window.addEventListener('load', reportPerformance); } // Error tracking window.addEventListener('error', function(event) { counter.reachGoal('js_error', { message: event.message, file: event.filename, line: event.lineno }); }); // Unhandled promise rejection window.addEventListener('unhandledrejection', function(event) { counter.reachGoal('promise_rejection', { reason: String(event.reason) }); }); ``` -------------------------------- ### Configure Custom Build Features Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Modify the features.json file to enable or disable specific features to control the final build size. ```json [ { "code": "GOAL_FEATURE", "disabled": false, "weight": 50 }, { "code": "CLICKS_FEATURE", "disabled": true // Exclude from build }, { "code": "CLICKMAP_FEATURE", "disabled": true // Exclude from build } ] ``` -------------------------------- ### Implement provider initialization Source: https://github.com/yandex/metrica-tag/blob/main/README.md Export an initProvider function in index.ts that uses feature flags to conditionally include provider code. ```typescript export const initProvider = () => { /* The code is wrapped by a feature flag. If the feature is not included into a build, the code is cut off by rollup. The resultant empty function is cut off as well */ if (flags.SOME_NEW_FEATURE) { // Required code providersSync.push(someNewProvider); // Optional code for any additional setup addMiddlewareForProvider(SOME_NEW_PROVIDER, watchSyncFlags(), 1); providerMap[SOME_NEW_PROVIDER] = useSenderWatch; nameMap[SOME_NEW_PROVIDER] = fullList; } }; ``` -------------------------------- ### Use Method Chaining Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Chain multiple counter methods together as they return the counter instance. ```javascript counter .params({ step: 1 }) .userParams({ id: userId }) .setUserID(userId) .accurateTrackBounce(30000); ``` -------------------------------- ### getCounterKey(counterOptions) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Generates a unique key for a counter based on provided options. ```APIDOC ## getCounterKey(counterOptions) ### Description Generates unique key for counter from options. ### Signature `function getCounterKey(options: CounterOptions): string;` ### Parameters - **options** (CounterOptions) - Counter initialization options ### Returns Unique counter identifier string ``` -------------------------------- ### Track Custom Events and Funnels in JavaScript Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Use this pattern to track multi-step conversion funnels and update user parameters dynamically as users progress through steps. ```javascript const counter = new Ya.Metrica({ id: 123456, params: { funnel: 'checkout' } }); // Funnel step tracking function startCheckout() { counter.reachGoal('funnel_step_1_cart_view'); updateFunnelParams(1); } function proceedToShipping() { counter.reachGoal('funnel_step_2_shipping'); updateFunnelParams(2); } function proceedToPayment() { counter.reachGoal('funnel_step_3_payment'); updateFunnelParams(3); } function completePurchase(orderId, amount) { counter.reachGoal('conversion', { order_id: orderId, amount: amount, funnel_completed: true }); updateFunnelParams(4); } function updateFunnelParams(step) { counter.params({ current_step: step, step_time: Date.now() }); } ``` -------------------------------- ### browserInfo(overrides?) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Retrieves browser and page information. ```APIDOC ## browserInfo(overrides?) ### Description Gets browser and page information. ### Parameters - **overrides** (Record) - Optional - Additional browser info flags to include ### Returns - BrowserInfo object with browser/page properties ``` -------------------------------- ### Configure Multiple Counters in HTML Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/integration-guide.md Initialize multiple Yandex Metrica counters on a single page to track different properties or application segments. ```html ``` -------------------------------- ### createEventEmitter() Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Creates a simple event emitter for pub/sub operations. ```APIDOC ## createEventEmitter() ### Description Creates a simple event emitter for pub/sub. ### Signature `function createEventEmitter(): { on(event: string, fn: (data: T) => void): void; emit(event: string, data: T): void; off(event: string, fn?: (data: T) => void): void; }` ``` -------------------------------- ### file(url) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Tracks a file or resource download click. ```APIDOC ## file(url) ### Description Tracks a file/resource download click. ### Parameters - **url** (string) - Required - URL of the file being downloaded ### Returns - Counter instance (for method chaining) ### Example ```javascript counter.file('/documents/whitepaper.pdf'); ``` ``` -------------------------------- ### reachGoal(goalName, rawParams?, rawCallback?, rawFnCtx?) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Sends information about a completed goal (conversion event). ```APIDOC ## reachGoal(goalName, rawParams?, rawCallback?, rawFnCtx?) ### Description Sends information about a completed goal (conversion event). ### Parameters - **goalName** (string) - Required - Goal identifier defined in counter settings - **rawParams** (object|function) - Optional - Parameters to send with the goal or callback function - **rawCallback** (function) - Optional - Function to call after goal is sent - **rawFnCtx** (any) - Optional - Context (this value) for callback function ### Returns - Counter instance (for method chaining) ``` -------------------------------- ### telemetry(data?) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Creates telemetry data for transmission. ```APIDOC ## telemetry(data?) ### Description Creates telemetry data for transmission. ### Signature `function telemetry(data?: Record): Telemetry;` ### Returns - **Telemetry** (object) - Timing and performance data. ``` -------------------------------- ### Track Goals with reachGoal Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Use reachGoal to track conversions. The method accepts an optional parameters object and a completion callback. ```javascript counter.reachGoal('purchase', { product_id: 'ABC123', amount: 99.99 }, function() { console.log('Purchase tracked'); }); ``` -------------------------------- ### Enable automatic link tracking Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Configure the counter to track links automatically rather than implementing manual tracking logic. ```javascript { trackLinks: true } ``` -------------------------------- ### Track clicks and downloads Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Use these methods to manually track file downloads and external links, or enable automatic link tracking with optional selectors. ```javascript // Manual tracking counter.file('http://example.com/document.pdf'); counter.extLink('https://external-site.com'); // Automatic tracking counter.trackLinks(true); // With selector counter.trackLinks('a.download-link'); // Add custom extension counter.addFileExtension('epub'); ``` -------------------------------- ### extLink(url) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Tracks an external link click. ```APIDOC ## extLink(url) ### Description Tracks an external link click. ### Parameters - **url** (string) - Required - URL of the external link ### Returns - Counter instance (for method chaining) ### Example ```javascript counter.extLink('https://external-site.com'); ``` ``` -------------------------------- ### loadScript(ctx, src, timeout?) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Loads external script with timeout. ```APIDOC ## loadScript(ctx, src, timeout?) ### Description Loads external script with timeout. ### Signature `function loadScript(ctx: Window, src: string, timeout?: number): Promise;` ### Parameters - **ctx** (Window) - Window object - **src** (string) - Script URL - **timeout** (number) - Optional - Load timeout in milliseconds ``` -------------------------------- ### Counter API Methods Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/00-START-HERE.md Common methods available on the counter instance for tracking goals, user parameters, and link interactions. ```javascript counter.reachGoal(goalName, params?, callback?); counter.params(name, value); counter.userParams(params); counter.getClientID(); counter.setUserID(userId); counter.notBounce(options?); counter.accurateTrackBounce(time?); counter.file(url); counter.extLink(url); counter.trackLinks(config); counter.addFileExtension(ext); counter.destruct(); ``` -------------------------------- ### iterateTaskWithConstraints(ctx, tasks, callback, scope, maxTime) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Executes an array of tasks with concurrency limits and time constraints. ```APIDOC ## iterateTaskWithConstraints(ctx, tasks, callback, scope, maxTime) ### Description Executes array of tasks with concurrency limit and time constraint. ### Parameters - **ctx** (Window) - Required - Window object - **tasks** (T[]) - Required - Array of tasks to execute - **callback** (Function) - Required - Function called for each task - **scope** (string) - Required - Scope identifier for error logging - **maxTime** (number) - Required - Maximum execution time per task in milliseconds ``` -------------------------------- ### Send a goal conversion event Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Use reachGoal to track specific user actions. The optional callback executes after the goal data is successfully sent. ```javascript counter.reachGoal('purchase', { product_id: 'abc123' }, function() { console.log('Goal sent'); }); ``` -------------------------------- ### reachGoal Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Tracks goal completions (conversions) using the Goal Provider. ```APIDOC ## reachGoal(goalName, params?, callback?, context?) ### Description Tracks goal completions (conversions). ### Parameters - **goalName** (string) - Required - Goal identifier - **params** (object|function) - Optional - Parameters or callback - **callback** (function) - Optional - Completion callback - **context** (any) - Optional - Callback context ### Returns - Counter instance ### Example ```javascript counter.reachGoal('purchase', { product_id: 'ABC123', amount: 99.99 }, function() { console.log('Purchase tracked'); }); ``` ``` -------------------------------- ### Extend Global Window Interface Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/types.md Defines Metrica-specific properties on the global Window interface to support library namespaces and constructors. ```typescript declare global { interface Window { [yaNamespace]?: yaNamespaceStorage & yaNamespaceMetrikaCounter; Ya?: { [constructorName]: MetrikaCounter; Metrica: MetrikaCounter; [key: string]: unknown; }; } } ``` -------------------------------- ### curry2SwapArgs(fn) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Curries a 2-argument function and swaps argument order. ```APIDOC ## curry2SwapArgs(fn) ### Description Curries a 2-argument function and swaps argument order. ### Signature `function curry2SwapArgs(fn: (a: A, b: B) => R): (b: B) => (a: A) => R;` ``` -------------------------------- ### Ya.Metrica.getCounters() Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Retrieves an array of all initialized counters with their current configuration state. ```APIDOC ## Ya.Metrica.getCounters() ### Description Returns an array of all initialized counters with their configuration state. ### Returns - **Array** - Array of counter objects containing: - **id** (number): Counter ID - **type** (number): Counter type - **clickmap** (boolean): Whether clickmap is enabled - **trackHash** (boolean): Whether hash tracking is enabled - **accurateTrackBounce** (boolean): Whether bounce tracking is enabled - **trackLinks** (boolean|string): Link tracking configuration ### Example ```javascript const counters = Ya.Metrica.getCounters(); console.log('Active counters:', counters); ``` ``` -------------------------------- ### Generate feature set Source: https://github.com/yandex/metrica-tag/blob/main/README.md Run the npm script to generate the feature set after updating features.json. ```bash npm run features ``` -------------------------------- ### Track file download Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Tracks a specific file or resource download click. ```javascript counter.file('/documents/whitepaper.pdf'); ``` -------------------------------- ### Configure Link Tracking Options Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/configuration.md Defines how link tracking is enabled using boolean flags, CSS selectors, or detailed object configurations. ```javascript trackLinks: true // Track all downloads + external links ``` ```javascript trackLinks: 'a[href^="/downloads/"]' // Track specific links ``` ```javascript trackLinks: { links: 'a.tracked-link', downloadFilter: /\.(pdf|zip|exe)$/i, excludeFilter: /internal\.example\.com/ } ``` -------------------------------- ### Absolute Import Syntax Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/modules.md Use absolute paths with the src/ prefix for all main code imports to maintain consistent module resolution. ```typescript import { flags } from '@inject'; import { getSender } from 'src/sender'; import { combineMiddlewares } from 'src/middleware/combine'; ``` -------------------------------- ### Protocol Endpoint Variants Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Comparison of standard and compact parameter naming conventions for different endpoints. ```text Standard: mc.yandex.ru with parameter names like page-url, page-ref ``` ```text Collect: collect.yandex.ru with parameter names like dl, dr (more compact) ``` -------------------------------- ### Batch parameters Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/README.md Send multiple parameters in a single call to reduce the number of network requests. ```javascript counter.params({ a: 1, b: 2, c: 3 }); ``` -------------------------------- ### Configure automatic link tracking Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Enables or customizes automatic tracking for file downloads and external links. ```javascript // Enable automatic tracking counter.trackLinks(true); // Or with custom configuration counter.trackLinks({ links: 'a[href$=".pdf"]' }); ``` -------------------------------- ### Retrieve initialized counters Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Returns an array of all currently initialized counter objects and their configuration states. ```javascript const counters = Ya.Metrica.getCounters(); console.log('Active counters:', counters); ``` -------------------------------- ### Wait for document body Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Returns a promise that resolves once the document body is available in the provided window context. ```typescript function waitForBody(ctx: Window): Promise; ``` -------------------------------- ### trackLinks(config) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-counter.md Configures automatic tracking of file downloads and external links. ```APIDOC ## trackLinks(config) ### Description Configures automatic tracking of file downloads and external links. ### Parameters - **config** (boolean|string|object) - Required - Configuration for link tracking (true, URL pattern, or object) ### Returns - Counter instance (for method chaining) ### Example ```javascript counter.trackLinks(true); ``` ``` -------------------------------- ### PolyPromise Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Promise polyfill for older browsers. ```APIDOC ## PolyPromise ### Description Promise polyfill for older browsers. ### Signature `class PolyPromise implements Promise { constructor(executor: (resolve: (value: T) => void, reject: (reason: any) => void) => void); then(onFulfilled?: (value: T) => R | Promise): PolyPromise; catch(onRejected?: (reason: any) => R): PolyPromise; }` ``` -------------------------------- ### waitForBody(ctx) Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/api-reference-utilities.md Returns promise that resolves when document body is available. ```APIDOC ## waitForBody(ctx) ### Description Returns promise that resolves when document body is available. ### Signature `function waitForBody(ctx: Window): Promise;` ``` -------------------------------- ### Listen for debug events Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Attach an event listener to the window object to capture and log counter initialization data for debugging purposes. ```javascript window.addEventListener('__ym-debug', function(e) { console.log('Counter initialized:', e.detail); }); ``` -------------------------------- ### params Source: https://github.com/yandex/metrica-tag/blob/main/_autodocs/providers.md Sends custom session parameters with all hits using the Parameters Provider. ```APIDOC ## params(name?, value?) ### Description Sends custom session parameters with all hits. Parameters are accumulated in the session and sent with every subsequent hit. ### Parameters - **name** (string|object) - Optional - Parameter name or object - **value** (any) - Optional - Parameter value ### Returns - Counter instance ### Example ```javascript counter.params('user_level', 'premium'); // Or multiple at once: counter.params({ user_level: 'premium', subscription_active: true }); ``` ```