Socket
Book a DemoInstallSign in
Socket

tg-mini-app-binder

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

tg-mini-app-binder

A modular and extendable wrapper for the Telegram Mini App API to simplify interactions between your web app and the Telegram client.

latest
Source
npmnpm
Version
1.0.2
Version published
Maintainers
1
Created
Source

Telegram Mini App Binder

A modular and extendable wrapper for the Telegram Mini App API (window.Telegram.WebApp). This library simplifies interactions between your web app and the Telegram client by providing a clean, object-oriented, and fully-documented interface.

It's designed to be lightweight, easy to use, and works seamlessly in both static web apps and modern JavaScript projects that use bundlers like Webpack or Rollup.

✨ Features

Modular Architecture: Functionality is split into logical modules (app, user, ui, messaging, links) for clarity and maintainability.

Simplified API: Abstracts away the raw Telegram.WebApp object into intuitive methods.

Mock Mode: Provides a mock object for easier development and testing outside the Telegram client, preventing crashes and logging actions to the console.

User Management: Easily access user data and the critical initData string for backend validation.

UI Controls: Effortlessly manage the Main Button, Back Button, and trigger Haptic Feedback.

Contact Request: A simplified, promise-based method to request the user's phone number.

Messaging: Send data from your Mini App directly to your bot.

App Lifecycle: Control the app by closing or expanding it, and listen for key events like theme changes.

Navigation: Open other Telegram Mini Apps, user profiles, or payment invoices.

🚀 Installation

You can use the library in two ways: by directly including it in your HTML or by installing it via NPM.

1. For Static Web Apps (HTML, JS)

If you are not using a bundler, you can include the library files directly in your HTML. Make sure to load the official Telegram script first.

<!-- 1. The official Telegram script -->
<script src="https://unpkg.com/tg-mini-app-binder@1.0.0/src/index.js"></script>

<!-- 2. The library modules -->
<script type="module" src="path/to/src/modules/WebAppModule.js"></script>
<script type="module" src="path/to/src/modules/UserModule.js"></script>
<script type="module" src="path/to/src/modules/MessagingModule.js"></script>
<script type="module" src="path/to/src/modules/UIModule.js"></script>
<script type="module" src="path/to/src/modules/LinksModule.js"></script>
<script type="module" src="path/to/src/index.js"></script>

<!-- 3. Your application logic -->
<script type="module" src="your-app.js"></script>

2. For Node.js Environments (with a bundler)

For projects using NPM and a bundler like Webpack, Rollup, or Vite:

  • Install the package:
npm install tg-mini-app-binder
  • Import and use it in your project:
import TelegramMiniAppBinder from 'tg-mini-app-binder';

const tgBinder = new TelegramMiniAppBinder();

// Now you can use the binder
console.log('User First Name:', tgBinder.user.getData()?.first_name);

📖 API Reference & Examples

First, instantiate the library. All functionalities are accessed through this instance.

const tgBinder = new TelegramMiniAppBinder();

App Module (tgBinder.app)

Manages general app properties and lifecycle events.

Close the App

// Closes the Mini App window
tgBinder.app.close();

Expand the App

// Expands the Mini App to its maximum height
tgBinder.app.expand();

Get Platform and Color Scheme

console.log('Platform:', tgBinder.app.getPlatform()); // "ios", "android", "desktop"
console.log('Color Scheme:', tgBinder.app.getColorScheme()); // "light" or "dark"

Others the App

/**
     * Returns the telegram object.
     */
    getTG(){
        return this.tg;
    }
      /**
     * Returns the Mini App SkD Version.
     * @param {string|object} version - contains title, message, buttons->optional
     */
    getVersion(version){
        return this.tg.isVersionAtLeast(version);
    }
    /**
     * Hides Keyboard.
     * 
     */
    hideKeyboard(){
        return this.tg.hideKeyboard();
    }
    /**
     * Request Emoji Status Access.
     * @param {object} callback - callback action
     */
    requestEmojiStatusAccess(callback){
        this.tg.requestEmojiStatusAccess(callback);
    }
    /**
     * Sets Emoji Status.
     * @param {object} custom_emoji_id - message_id
     * @param {string | object } params - json
     * @param {object} callback - callback action
     */
    setEmojiStatus(custom_emoji_id, params, callback){
        this.tg.setEmojiStatus(custom_emoji_id, params, callback);
    }
    /**
     * Share Mesage.
     * @param {object} msg_id - message_id
     * @param {object} callback - callback action
     */
    shareMessage(msg_id, callback){
        this.tg.shareMessage(msg_id, callback);
    }
     /**
     * Share To Story.
     * @param {object} media_url - callback action
     * @param {string | object } params - json
     */
    shareToStory(media_url, params){
        this.tg.shareToStory(media_url, params);
    }
    /**
     * Downloads File.
     * @param {object} callback - callback action
     * @param {string | object } params - json
     */
    downloadFile(params, callback){
        this.tg.downloadFile(params, callback);
    }
     /**
     * Requests Contact.
     * @param {object} callback - callback action
     */
    requestContact(callback){
        this.tg.requestWriteAccess(callback);
    }
     /**
     * Requests Write Access.
     * @param {object} callback - callback action
     */
    requestWriteAccess(callback){
        this.tg.requestWriteAccess(callback);
    }
     /**
     * Read Text From Clipboard.
     * @param {object} callback - callback action
     */
    readTextFromClipboard(callback){
        this.tg.readTextFromClipboard(callback);
    }
    /**
     * Adds The Mini App to the Home Screen.
     * 
     */
    addToHomeScreen(){
        this.tg.addToHomeScreen();
    }
    /**
     * Disables Vertical Swip.
     * 
     */
    disableVerticalSwipes(){
        this.tg.disableVerticalSwipes();
    }
    /**
     * Enable Vertical Swip.
     * 
     */
    enableVerticalSwipes(){
        this.tg.enableVerticalSwipes();
    }
    /**
     * Disable Close Confirmation.
     * 
     */
    disableCloseConfirmation(){
        this.tg.disableClosingConfirmation();
    }
    /**
     * Enables Close Confirmation.
     * 
     */
    enableCloseConfirmation(){
        this.tg.enableClosingConfirmation();
    }
    /**
     * Show Popup in the Mini App.
     * @param {string|object} orientation - contains title, message, buttons->optional
     */
    fullScreenAndLock(orientation){
        this.tg.requestFullscreen();
        this.tg.lockOrientation(orientation);
    }
    /**
     * Enebles FullScreen Mode.
     */
    fullScreen(){
        this.tg.requestFullscreen();
        this.tg.lockOrientation();
    }
        /**
     * Exit FullScreen.
     */
    exitfullScreen(){
        this.tg.exitFullscreen();
        this.tg.unlockOrientation();
    }
   /**
     * Show Popup in the Mini App.
     * @param {JSON} data - contains title, message, buttons->optional
     * @param {object} callback - callback action
     */
    showPopup(data, callback ){
        this.tg.showPopup(data, callback);
    }
   /**
     * Show Alert in the Mini App.
     */
    showAlert(data, callback){
        this.tg.showAlert(data, callback);
    }
    /**
     * Show confirm in the Mini App.
     */
    showConfirm(data, callback){
        this.tg.showAlert(data, callback);
    }
   /**
     * open qr scanner.
     */
    showScanQrPopUp(data, callback) {
        this.tg.showScanQrPopUp(data, callback);
    }
       /**
     * Closes the qr scaner.
     */
    closeScanQrPopUp(){
        this.tg.closeScanQrPopUp();
    }
    /**
     * Closes the Mini App.
     */
    close() {
        this.tg.enableClosingConfirmation();
        this.tg.close();
    }

    /**
     * Expands the Mini App to its maximum height.
     */
    expand() {
        this.tg.expand();
    }

    /**
     * Checks if the Mini App is expanded.
     * @returns {boolean}
     */
    isExpanded() {
        return this.tg.isExpanded;
    }

    /**
     * Returns the platform the app is running on.
     * @returns {'ios' | 'android' | 'desktop' | 'test'}
     */
    getPlatform() {
        return this.tg.platform;
    }

    /**
     * Returns the color scheme of the Telegram app.
     * @returns {'light' | 'dark'}
     */
    getColorScheme() {
        return this.tg.colorScheme;
    }

Listen for Events

// Fired when the user's Telegram theme changes
tgBinder.app.onEvent('themeChanged', () => {
    console.log('Theme has changed to:', tgBinder.app.getColorScheme());
    // You can update your app's CSS variables here
});

// Fired when the viewport size changes (e.g., keyboard appears)
tgBinder.app.onEvent('viewportChanged', () => {
    console.log('Viewport height is now:', tgBinder.tg.viewportHeight);
});

User Module (tgBinder.user)

Handles user-related data.

Get User Data This data is "unsafe" and should only be used for display purposes. For authentication, validate the initData on your backend.

const user = tgBinder.user.getData();
if (user) {
    console.log(`Hello, ${user.first_name}!`);
    // user object: { id, first_name, last_name?, username?, language_code, is_premium? }
}

Get Init Data This is the raw, encrypted data string you should send to your backend for validation to authenticate the user.

const initData = tgBinder.user.getInitData();
// Send this 'initData' string to your backend
fetch('/your-api/authenticate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ initData })
});

Messaging Module (tgBinder.messaging)

Manages sending data to your bot.

Request Access Prompts the user for permission to send messages to them via the bot.

const messageAccess = tgBinder.messaging.requestWriteAccess();

Send Data to Bot The bot will receive this as a web_app_data message in the chat.

const orderData = {
    productId: 'item-123',
    quantity: 2,
    timestamp: new Date().toISOString()
};

// The library automatically stringifies the object
tgBinder.messaging.sendData(orderData);

UI Module (tgBinder.ui)

Controls native Telegram UI elements.

Request User's Phone Number This method configures the MainButton to ask for the user's contact information.

tgBinder.ui.requestContact({
    text: "Share Contact to Proceed",
    onSuccess: (granted) => {
        console.log('Contact access request sent!', granted); // true
        // The bot will receive the contact information
    },
    onFailure: () => {
        console.log('User denied contact access.');
    }
});

Trigger Haptic Feedback Provide tactile feedback for user actions.

// For light taps (e.g., selecting an option)
tgBinder.ui.impactOccurred('light');

// For notifications (e.g., action completed successfully)
tgBinder.ui.notificationOccurred('success');

// For errors
tgBinder.ui.notificationOccurred('error');

//Sets the bottom bar color.
tgBinder.ui.setBottomBarColor(color)


//Sets the background color.
tgBinder.ui.setBackGroundColor(color)

//Sets the header color.
tgBinder.ui.setHeaderColor(color)

    /**
     * Configures and shows the MainButton to request the user's phone number.
     * Listens for the mainButtonClicked event to handle the response.
     * @param {object} options - Configuration for the button.
     * @param {string} options.text - The text to display on the button (e.g., "Share Phone Number").
     * @param {Function} options.onSuccess - Callback fired with `true` when the request is sent.
     * @param {Function} options.onFailure - Callback fired if the user denies the request or an error occurs.
     */
tgBinder.ui.requestContact({ text = "Share Contact", onSuccess, onFailure })

Handles opening other Telegram links.

Open Another Mini App or a Telegram Link You can use this to navigate between different Mini Apps or to a user's profile.

// URL to another bot's Mini App
const anotherAppUrl = 'https://t.me/notcoin_bot'; // Example with Notcoin

tgBinder.links.openTelegramLink(anotherAppUrl);

// 'try_browser'
tgBinder.links.openLink(anotherAppUrl, 'try_instant_view')

Open a Payment Invoice Open an invoice link generated by your bot.

const invoiceUrl = 'https://t.me/invoice/your_invoice_payload';

tgBinder.links.openInvoice(invoiceUrl, (status) => {
    // This callback is fired when the invoice is closed
    console.log(`Invoice closed with status: ${status}`); // 'paid', 'cancelled', 'failed', 'pending'
});

🔧 Mock Mode for Development

When you run your web app in a regular browser (not inside Telegram), the library automatically enters mock mode. All function calls will be logged to the console instead of throwing errors. This allows you to develop and test your app's UI and logic without needing to constantly deploy to a server.

// Console output when running in a normal browser:
[Mock Mode] Mock App Ready
[Mock Mode] Mock Haptic Impact: medium
[Mock Mode] Mock opening Telegram link: https://t.me/notcoin_bot

🤝 Contributing

Contributions, issues, and feature requests are welcome! Feel free to check the issues page for this project.

author y0red

📄 License

This project is MIT licensed.

Keywords

telegram

FAQs

Package last updated on 06 Sep 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts