Skip to main content

Overview

The Dashgram JavaScript SDK is a lightweight analytics library for Telegram Mini Apps built with vanilla JavaScript, TypeScript, or any web framework. It automatically tracks user interactions and sends analytics data to Dashgram.
This SDK is specifically designed for Telegram Mini Apps. It requires your application to be running inside Telegram’s WebApp environment.

Getting Started

1. CDN

Add these scripts to your HTML before the closing </head> tag:
<script src="https://telegram.org/js/telegram-web-app.js"></script>
<script src="https://unpkg.com/@dashgram/javascript@latest/dist/dashgram.min.js"></script>

2. Initialize the SDK

Initialize Dashgram inside </body>:
<script>
  DashgramMini.init({
    projectId: "your-project-id",
    trackLevel: 3
  })
</script>
Required Configuration: Optional Configuration:
  • trackLevel - Event collection level: 1, 2, or 3 (default: 2)
  • debug - Enable debug logging (default: false)
  • disabled - Disable all tracking (default: false)
  • batchSize - Number of events to batch before sending (default: 10)
  • flushInterval - Milliseconds between automatic flushes (default: 5000)
  • apiUrl - Custom API endpoint (default: https://api.dashgram.io/v1)
  • onError - Error callback function

3. Track Custom Events (optional)

If you want to send custom events to Dashgram, use the DashgramMini.track() method. Simply call it with an event name and optional properties whenever the action happens.
DashgramMini.track("purchase_completed", {
  product_id: "premium-plan",
  price: 100,
  currency: "TON"
})

Complete Example

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>My Mini App</title>

    <!-- Telegram WebApp SDK -->
    <script src="https://telegram.org/js/telegram-web-app.js">
    <!-- Telegram Dashgram SDK -->
    <script src="https://unpkg.com/@dashgram/javascript@latest/dist/dashgram.min.js"></script>
  </head>
  <body>
    <h1>My Mini App</h1>
    <button id="purchase-btn">Purchase Premium</button>

    <script>
      // Initialize Dashgram
      DashgramMini.init({
        projectId: "your-project-id",
        trackLevel: 2,
        debug: true // Enable in development
      })

      // Track custom events
      document.getElementById("purchase-btn").addEventListener("click", () => {
        DashgramMini.track("purchase_initiated", {
          product_id: "premium-plan",
          price: 100,
          currency: "TON"
        })
      })
    </script>
  </body>
</html>

Track Levels

Dashgram offers three tracking levels to balance data collection and performance:

Level 1 - Core

Minimal tracking - Basic app lifecycle events only.
EventDescription
app_openMini App opened or became visible
app_closeMini App closed or hidden
Use when: You only need basic usage metrics. Standard tracking - Level 1 + user interactions.
EventDescription
screen_viewPage/route navigation
button_clickButton clicks
link_clickLink clicks (external detection)
form_submitForm submissions
input_focusInput field focus
input_changeInput field value changed
copyText copied to clipboard
cutText cut to clipboard
pasteText pasted from clipboard
text_selectText selection
js_errorJavaScript errors
unhandled_rejectionUnhandled Promise rejections
Use when: You want standard web analytics (recommended for most apps).

Level 3 - Deep Analytics

Comprehensive tracking - Level 1 + 2 + performance metrics + all Telegram events.
EventDescription
scroll_depthScroll milestone reached
element_visibleTracked element became visible
rage_clickRapid repeated clicks
long_taskJS task >50ms
web_vital_lcpLargest Contentful Paint
web_vital_fidFirst Input Delay
web_vital_clsCumulative Layout Shift
network_statusOnline/offline status
orientation_changeDevice orientation change
media_play/pause/endedVideo/audio events
telegram_theme_changedTelegram theme change
telegram_viewport_changedViewport size change
telegram_main_button_clickedMain button pressed
telegram_back_button_clickedBack button pressed
telegram_invoice_closedInvoice closed
…and all other Telegram events
Use when: You need detailed performance monitoring and all Telegram WebApp events.

TypeScript Support

The SDK includes full TypeScript definitions:
import DashgramMini, { DashgramConfig, EventProperties, TrackLevel } from "@dashgram/javascript"

const config: DashgramConfig = {
  projectId: "your-project-id",
  trackLevel: 2 as TrackLevel
}

DashgramMini.init(config)

const properties: EventProperties = {
  product_id: "premium-plan",
  price: 100
}

DashgramMini.track("purchase_completed", properties)

API Reference

DashgramMini.init(config)

Initialize the SDK. Must be called once when your app loads. Parameters:
ParameterTypeRequiredDefaultDescription
projectIdstringYesYour project ID from Dashgram dashboard
trackLevel1 | 2 | 3No2Event collection level
debugbooleanNofalseEnable debug logging to console
disabledbooleanNofalseDisable all tracking
batchSizenumberNo10Number of events to batch before sending
flushIntervalnumberNo5000Milliseconds between automatic flushes
apiUrlstringNohttps://api.dashgram.io/v1Custom API endpoint
onErrorfunctionNoCallback for handling errors
Example:
DashgramMini.init({
  projectId: "your-project-id",
  trackLevel: 2,
  debug: false,
  batchSize: 20,
  flushInterval: 10000,
  onError: error => {
    console.error("Dashgram error:", error)
  }
})

DashgramMini.track(event, properties)

Track a custom event with optional properties. Parameters:
  • event (string) - Event name
  • properties (object, optional) - Event properties
Example:
DashgramMini.track("button_clicked", {
  button_name: "purchase",
  product_id: "premium-plan",
  price: 100,
  currency: "TON"
})

DashgramMini.flush()

Force send all pending events immediately. Returns a Promise. Use cases:
  • Before page unload
  • After critical user actions
  • When switching users
Example:
// Flush before page unload
window.addEventListener("beforeunload", () => {
  DashgramMini.flush()
})

// Or use async/await
await DashgramMini.flush()

DashgramMini.shutdown()

Stop tracking and clean up resources. Useful for:
  • User opt-out scenarios
  • App cleanup
  • Testing
Example:
// User opts out of tracking
DashgramMini.shutdown()

Best Practices

1. Initialize Early

Initialize Dashgram as early as possible in your app lifecycle:
// Good: Initialize immediately
<script>
  DashgramMini.init({ projectId: "your-project-id" })
</script>

// Avoid: Initializing after user interaction
button.addEventListener("click", () => {
  DashgramMini.init({ projectId: "your-project-id" }) // Too late!
})

2. Use Meaningful Event Names

Use clear, descriptive event names:
// Good
DashgramMini.track("purchase_completed", { product_id: "premium" })
DashgramMini.track("user_signed_up", { method: "telegram" })

// Avoid
DashgramMini.track("click", {})
DashgramMini.track("event1", {})

3. Flush Before Unload

Ensure events are sent before the user leaves:
window.addEventListener("beforeunload", () => {
  DashgramMini.flush()
})

4. Handle Errors Gracefully

Use the onError callback to handle errors:
DashgramMini.init({
  projectId: "your-project-id",
  onError: error => {
    // Log to your error tracking service
    console.error("Analytics error:", error)
    // Don't break your app if analytics fails
  }
})

5. Respect User Privacy

Allow users to opt out:
// User opts out
if (userOptedOut) {
  DashgramMini.init({
    projectId: "your-project-id",
    disabled: true
  })
}

Troubleshooting

Events Not Sending

  1. Check initialization: Ensure DashgramMini.init() is called
  2. Verify project ID: Make sure your project ID is correct
  3. Check Telegram environment: SDK only works inside Telegram WebApp
  4. Enable debug mode: Set debug: true to see console logs
DashgramMini.init({
  projectId: "your-project-id",
  debug: true // Check console for logs
})

SDK Not Detecting Telegram

The SDK automatically detects if it’s running in Telegram. If events aren’t being tracked:
  1. Ensure you’re testing inside Telegram (not a regular browser)
  2. Make sure telegram-web-app.js is loaded before Dashgram SDK
  3. Check that Telegram WebApp API is available: window.Telegram?.WebApp

Next Steps