TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits
The Telegram widget API is the window.TelegramWidget object that every Bot API 10.4 widget gets from the Telegram app, plus the Bot API side: widget_query updates and answerWidgetQuery. This reference lists every property, method, event and error code of TelegramWidget, the CSS variables, the gesture rules and the limits, based on the official Telegram widgets documentation.
Availability: in the production environment widgets currently work only in the private chat with the bot and can't be forwarded (they're sent with protected content). Groups, inline mode and forwards work only on the test server, so properties likeisForwardorchatType: "group"matter there first.
New to widgets? Start with what Telegram widgets are and the widget examples.
How the TelegramWidget object appears
Widgets need no script tag. Inside Telegram, window.TelegramWidget exists before the widget's first script runs. Outside Telegram (a plain browser) it is undefined. Methods added within a profile are detected with typeof:
const W = window.TelegramWidget; // undefined in a normal browser
if (W && typeof W.setResizeAnchor === 'function') W.setResizeAnchor('bottom');
function render() {
let state = null;
try { state = JSON.parse(W.chatData); } catch (e) {}
// draw from state; null means "no state yet"
}
if (W) W.onEvent('chatDataChanged', render);
render();
TelegramWidget properties
| Property | Type | Description |
|---|---|---|
profile | Integer | The widget profile the app enforces: 1 in this version |
colorScheme | String | light or dark, the chat's scheme (also --tg-color-scheme) |
themeParams | Object | The bubble's palette as #rrggbb strings, with the keys of Mini Apps' themeParams |
isActive | Boolean | The widget is visible (!document.hidden) |
isPreview | Boolean | An inline result shown before sending: no taps, no requests |
isForward | Boolean | A forwarded copy |
chatType | String | private, group, supergroup, channel, or null in a forward or preview |
viewer | Object | id, first_name, last_name, username, is_premium of the user looking; only where the widget may send requests, otherwise null |
publicData | String | The shared state, up to 1024 bytes, or null. Read-only |
chatData | String | The chat state, up to 1024 bytes, or null; always null in a forward. Read-only |
contentSafeAreaInset | Object | top, right, bottom, left, cornerLeft, cornerRight: the part covered by the message time |
wallet | Object | Telegram's wallet, or null (no wallet in this app, no requests allowed, a preview) |
HapticFeedback | Object | Haptic feedback, see below |
TelegramWidget methods
| Method | What it does |
|---|---|
request(data[, options]) | Sends 1–64 bytes to the bot. Returns a Promise of { result } (the bot's answer or null) or rejects with WidgetRequestError. Only in a tap handler, or in the background where allowed. options may be { wallet: true } |
watchPublicData() / unwatchPublicData() | Start / stop live polling of a shared widget's shared state while on screen. No effect on a static widget or in a preview |
copyText(text) | Copies 1–256 characters on a tap; the app shows a toast with the text |
openLink(url) | Opens an https: URL (≤ 256 characters, not a t.me host) after the user confirms |
openTelegramLink(url) | Opens a https://t.me/… link inside Telegram, like a tapped link in a message |
setResizeAnchor(edge) | top (default) or bottom: which bubble edge stays in place when the height changes |
ready() | Optional: tells the app the first state is drawn |
onEvent(type, handler) / offEvent(type, handler) | Add / remove an event handler (at most 16 per event type) |
isProfileAtLeast(n) | Returns profile >= n |
All methods are synchronous except isProfileAtLeast, request and the wallet methods. HapticFeedback has impactOccurred(style) (light, medium, heavy, rigid, soft), notificationOccurred(type) (error, success, warning) and selectionChanged(). There is no sendMessage, and the widget is not told its widget_id.
Events
| Event | When |
|---|---|
themeChanged | The chat theme changed; colorScheme, themeParams and CSS variables are already updated |
activated / deactivated | The widget became visible / hidden (after visibilitychange) |
chatDataChanged | The bot changed the chat state; chatData is already new. Never in a forward |
publicDataChanged | The bot changed the shared state; for a shared widget on screen only while it watches. Fires after chatDataChanged when both change |
contentSafeAreaChanged | The area covered by the message time changed (caption added, removed or moved, "edited" mark) |
Handlers are called with this bound to TelegramWidget and no arguments, so read the new values from the object.
WidgetRequestError codes
button.addEventListener('click', () => {
status.textContent = 'Sending…';
TelegramWidget.request('vote:2').then(
(answer) => { status.textContent = answer.result ?? 'Done'; },
(error) => { status.textContent = 'Error: ' + error.code; }, // error.name === 'WidgetRequestError'
);
});
| code | Meaning |
|---|---|
NOT_ALLOWED | No allow_queries, a forward of a static widget, no tap where background requests are off, a preview, or an app that does not deliver requests |
BUSY | Another request or wallet call of this widget is in flight |
RATE_LIMITED | A background call within 5 seconds of the last one, or over 5 requests per 5 seconds per user and bot |
TIMEOUT | The bot did not answer in 15 seconds (down, slow, or not receiving widget_query / shared_widget_query) |
FAILED | Anything else: the bot was blocked or deleted, the message is gone, the network failed |
INVALID_ANSWER | The bot's answer broke the limits |
REJECTED, BAD_REQUEST | Wallet calls only: the user declined, or the wallet refused the transaction or payload |
Data that is empty or over 64 bytes throws TypeError before anything is sent.
The bot side: widget_query and answerWidgetQuery
A request from an original message arrives as widget_query in the Update; one from a forwarded shared widget as shared_widget_query. If you pass allowed_updates to getUpdates or setWebhook, include both.
{
"update_id": 100000001,
"widget_query": {
"id": "8123456789012345678",
"from": {"id": 123456789, "is_bot": false, "first_name": "Alice"},
"chat": {"id": 123456789, "type": "private", "first_name": "Alice"},
"message_id": 4242,
"chat_instance": "901234567890123456",
"type": {"type": "data"},
"data": "refresh"
}
}
A widget_query from a message sent via the bot has inline_message_id and chat_type instead of chat and message_id; widget_id is present for shared widgets. A shared_widget_query has only id, from, type, data and widget_id. Answer every query with answerWidgetQuery (widget_query_id, optional data up to 1024 bytes); change the state separately with editMessageWidgetData or editSharedWidgetData. from and widget_id are set by Telegram and can't be forged, but treat data as untrusted input.
curl -X POST "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/answerWidgetQuery" \
-H "Content-Type: application/json" \
-d '{"widget_query_id": "8123456789012345678", "data": "{\"n\":5,\"r\":3}"}'
CSS variables
| Variable | Meaning |
|---|---|
--tg-theme-bg-color, --tg-theme-text-color, --tg-theme-hint-color, --tg-theme-link-color | Bubble background, text, secondary text, links |
--tg-theme-button-color, --tg-theme-button-text-color | The app's primary button |
--tg-theme-secondary-bg-color, --tg-theme-accent-text-color, --tg-theme-subtitle-text-color, --tg-theme-destructive-text-color, --tg-theme-section-separator-color | Second surface, accent, subtitles, destructive actions, separators |
--tg-color-scheme | light or dark |
--tg-text-font-size, --tg-text-line-height, --tg-text-padding | Message text size (about 15px), line height (about 1.35), bubble text inset (about 8px 12px) |
--tg-button-bg, --tg-button-text, --tg-button-radius, --tg-button-font, --tg-button-padding, --tg-button-height, --tg-button-pressed-opacity, --tg-button-disabled-opacity | The app's button style used by the default <button> |
--tg-content-safe-area-inset-*, --tg-content-safe-area-corner-left / -right | The band where the message time is drawn (same as env(safe-area-inset-*)) |
The app sets these on the root element with !important; you can only redefine them on your own elements. prefers-color-scheme, light-dark() and color-scheme follow the chat theme, not the system.
Gestures and touch-action
Taps and double taps are always the widget's; vertical drags always scroll the chat (the widget gets pointercancel). Holds and horizontal drags are claimed per element with CSS touch-action: auto leaves them to the chat (message menu, swipe-to-reply), pan-y gives horizontal drags to the widget, none gives it holds (contextmenu) and horizontal drags. Rule of thumb: touch-action: none on a hold button, game control or canvas, pan-y on a horizontal slider or carousel, auto everywhere else. Use pointer events; touch events are not delivered. Keep controls away from the leading 20 px, which never take a claim.
What the widget profile removes
- Form controls (
input,select,textarea);<button>is the only control. No keyboard events or focus. - Every network API (
fetch,XMLHttpRequest,WebSocketand others throwNetworkDisabledError), external scripts, styles, fonts and images,locationandhistory. vhand other height-relative units,overflow: auto / scroll(becomeshidden),position: sticky,@font-face,:has(), CSS nesting.alert,confirm,prompt,navigator.clipboard(usecopyText),iframe,video,audio, WebGL.
Removed features never break the widget: the element, declaration or event is dropped and the rest keeps working. CSS.supports() and @supports answer according to the profile.
Telegram widget limits
| Limit | Value | Beyond it |
|---|---|---|
| HTML | 32768 bytes; 4096 bytes after zlib level 9 | INPUT_MEDIA_WIDGET_TOO_LARGE |
chat_data, public_data | 1024 bytes of UTF-8 each | INPUT_MEDIA_WIDGET_DATA_TOO_LARGE |
| Request data | 1–64 bytes | TypeError in the widget |
| Answer data | 1024 bytes | WIDGET_RESULT_TOO_LARGE |
| Time to answer | 15 seconds | TIMEOUT; late answer: query is too old |
| Requests | 5 per 5 seconds per user and bot | RATE_LIMITED |
| Shared widget edits | 1 per second; refresh period 30 s by default, cache_time 5–3600 | Flood wait; invalid cache time specified below 5 |
| CPU | 300 ms of JavaScript per second; 500 ms in one task | Throttled; the widget is stopped |
| Memory | 8 MB | The widget is stopped |
| DOM nodes | 2000 | The widget is stopped |
| Timers | 64 live timers | RangeError |
localStorage, sessionStorage | 4 KB per area per message | QuotaExceededError |
| Bubble | 200 px to the bubble's maximum wide, 50–600 px tall | Clipped |
A stopped widget keeps its last frame with a "Widget stopped" badge and is rebuilt when shown again; after two crashes in a row it stays stopped until the app restarts.
Storage, links, haptics and copyText
- Web Storage belongs to this message on this device. It survives app restarts, is never sent to the bot and is not synced between devices. Wrap
setItemintry/catch. - Links:
openLink,openTelegramLink,copyTextandrequestneed a real tap: call them synchronously in aclickhandler, not afterawaitor a timer. One tap unlocks one such call. An invalid URL throwsTypeError; a tapped<a href="https://…">works too. - Haptics play only while the widget is visible, at most 5 in a burst and 10 per second; they are free during a touch and for 5 seconds after it. Desktop and web apps play nothing.
- copyText copies 1–256 characters and always shows a toast with the copied text.
TON wallet payments in brief
A widget can ask the user to pay through Telegram's built-in wallet, using TON Connect formats. Draw a pay button only when TelegramWidget.wallet is not null. On a tap, the widget sends request(data, { wallet: true }); the bot's query then has type {"type": "data", "wallet_card": …}, and the bot answers with a fresh transaction. In the answer's handler, the widget calls wallet.sendTransaction(), which needs no second tap within 10 seconds:
TelegramWidget.request('pay:42', { wallet: true })
.then((a) => TelegramWidget.wallet.sendTransaction(JSON.parse(a.result), 'paid:42'))
.then((a) => show(a.result), (e) => showError(e.code));
The bot then receives a query of type sent_transaction with the message hash and must verify the transaction on the chain. After TIMEOUT the payment may have gone through, so ask the bot about the order instead of paying again.
Bot API errors for widgets
| Error | Cause |
|---|---|
INPUT_MEDIA_WIDGET_TOO_LARGE | HTML over 32768 bytes or 4096 bytes compressed |
INPUT_MEDIA_WIDGET_HTML_INVALID | Invalid UTF-8 or a NUL character in html |
INPUT_MEDIA_WIDGET_DATA_TOO_LARGE | chat_data or public_data over 1024 bytes |
INPUT_MEDIA_WIDGET_DATA_INVALID / WIDGET_DATA_INVALID | Invalid state text when sending / when editing |
message is not modified | An edit that changes nothing; treat it as success |
Try the methods with your own token in the Bot API Tester, and see the parameters of sendWidget. For the full 10.4 release notes, read what's new in Bot API 10; for testing the bigger sibling, how to test a Telegram Mini App.
Frequently asked questions
Do I need to include a script to use TelegramWidget?
No. Inside Telegram, window.TelegramWidget exists before the widget's first script runs, with the state, theme and context already in place. Outside Telegram it is undefined, so check for it when you open the widget in a browser.
What does WidgetRequestError NOT_ALLOWED mean?
The message may not send requests: the widget was sent without allow_queries, it is a forward of a static widget or a preview, or request() was called outside a tap where background requests are off.
How fast must a bot answer a widget_query?
Within 15 seconds, with answerWidgetQuery. After that the widget's promise rejects with TIMEOUT and a late answer is refused with query is too old. Answer every query, even when something failed.
Can a widget change its own chatData or publicData?
No. Both are read-only in the widget. Only the bot writes the state, with sendWidget, editMessageWidgetData or editSharedWidgetData; the widget can only ask the bot with TelegramWidget.request().
Is there a TelegramWidget.sendMessage method?
No. sendMessage does not exist in widgets: nothing is ever sent to the chat on the user's behalf. The widget can only send requests to its bot, copy text, open links and play haptics.
Related guides
How to Create a Telegram Bot: Step by Step with BotFather and Python
How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.
Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More
What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.
Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length
Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.
How to Send a Message with the Telegram Bot API (sendMessage)
Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.
Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe
Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.
How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting
Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.
How to Get a Telegram Chat ID for a User, Group, Channel or Topic
How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.
Telegram Test Server: How to Test a Bot in the Telegram Test Environment
Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.
Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button
Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.
Telegram Widget Examples: Complete HTML and Python Bot Code
Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.
Telegram Widgets: Interactive HTML Inside Bot Messages
Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.
How to Test a Telegram Mini App: From Browser Mock to Real Telegram
Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.