Error could not initialize webview telegram

Steps to reproduce select checkout in telegram channel press "PAY xxx,xx RUB" button some second await and I see: "Error: Could not initialize WebView." Expected behaviour open ...

@kasumiru

Steps to reproduce

  1. select checkout in telegram channel
  2. press «PAY xxx,xx RUB» button
  3. some second await and I see: «Error: Could not initialize WebView.»

Expected behaviour

open payments web site or paymets window

Actual behaviour

see erorr: «Error: Could not initialize WebView»

Operating system

windows 10 build 19042.1348

Version of Telegram Desktop

3.2.5

Installation source

Static binary from official website

Logs

I can attach full log if it needed.

[2021.11.25 00:42:55] OpenGL: QOpenGLContext created, version: 3.3.
[2021.11.25 00:42:55] OpenGL: [TRUE] (OverlayWidget)
[2021.11.25 00:42:56] Message Info: bad message notification received (error_code 33) for msg_id = 7034255246324421704, seq_no = 42
[2021.11.25 00:42:56] Message Info: bad message notification received, msgId 7034255246324421704, error_code 33
[2021.11.25 00:42:56] API Warning: not loaded minimal channel applied.
[2021.11.25 00:42:56] API Warning: not loaded minimal channel applied.
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)

@Serge-Mazur

@jackvote

I confirm.
Operating system: windows 7
Version of Telegram Desktop: 3.5.1

The same problem on win10 was solved by an update Microsoft Edge.

On win7, I installed webview2. After that, I installed MS Edge.
The problem has not been fixed.

People can’t use Telegram Bot Payments on Win7

Tested on https://t.me/niloffffbot and others. Different payment systems.

@kasumiru

@lp85d

Durger King
Error: Could not initialize WebView.
How to solve the problem?
Telegram Desktop 💕
Версия 3.7 x64 — О программе

@IlhomjonMuxtorov

Durger King Error: Could not initialize WebView. How to solve the problem? Telegram Desktop 💕 Версия 3.7 x64 — О программе

I have same problem

OS — Windows 10
Telegram Desktop — 3.7 x64

@Aokromes

@IlhomjonMuxtorov

try 3.7.1

Again same problem

@ilya-fedin

Again same problem

Can you take a screenshot of the error?

@IlhomjonMuxtorov

Again same problem

Can you take a screenshot of the error?

web_app_wrong
web_app_wrong2
My desktop telegram version 3.7.3

@ilya-fedin

My desktop telegram version 3.7.3

Can you provide the logs?

@IlhomjonMuxtorov

My desktop telegram version 3.7.3

Can you provide the logs?

[2022.04.30 09:10:21] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)
[2022.04.30 09:11:59] API Warning: not loaded minimal channel applied.
[2022.04.30 09:11:59] API Warning: not loaded minimal channel applied.
[2022.04.30 09:12:16] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)

@ilya-fedin

[2022.04.30 09:10:21] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)

Do you by any chance use some kind of shrunk/modified version of Windows (debloated, despyed, etc)?

@IlhomjonMuxtorov

You are right, my windows is not offical

@ilya-fedin

You are right, my windows is not offical

That’s most likely the reason. Apparently the service tdesktop uses was ‘debloated’.

@IlhomjonMuxtorov

Web view working on offical windows

@ilya-fedin

@kasumiru can you confirm you use non-offical Windows, too?

@IlhomjonMuxtorov

That’s most likely the reason. Apparently the service tdesktop uses was ‘debloated’.

How can I fix it?

@ilya-fedin

How can I fix it?

Well, don’t use shrunk OS

@IlhomjonMuxtorov

@IlhomjonMuxtorov

But payment method web view working on my windows

@ilya-fedin

But payment method web view working on my windows

Are you sure? Can you provide a screenshot?

@ilya-fedin

@IlhomjonMuxtorov

This is not a webview.

Understood, thank you

@lp85d

Ошибка Durger King : не удалось инициализировать WebView. Как решить проблему? Телеграмма для рабочего стола💕 Версия 3.7 x64 — О программа

А всего та надо было установить MicrosoftEdgeWebview2

@ilya-fedin

It’s for Windows 11+. On Windows 8.1-10 tdesktop prefers the built-in Edge engine.

@github-actions
github-actions
bot

locked as resolved and limited conversation to collaborators

Jun 18, 2022

30 апреля 2022

Пример веб бота для телеграм

Ошибка в десктоп версии telegram Error: Could not initialize WebView.

Свидетельствует об отсутствии модуля MicrosoftEdgeWebview2

Так же запустить не получится в операционных системах моложе Windows 8.1

К сожалению. Вы не можете открыть данное меню с текущей конфигурацией системы.
Please update your system to Windows 8.1 or later.

На видео ниже пример Telegram WEB BOT тестируем на Android версии телеграм 8.7.2:

И установка MicrosoftEdgeWebview2 решила проблему с Telegram Desktop версией приложения телеграм Error: Could not initialize WebView.

После установки модуля веб бот отображается как планировалось

Вот такая ошибка была:

ms-settings:personalization-background X ©This file does not have a program associated with it for performing this action. Please install a program or, if one is already installed, create an association in the Default Programs control panel.

Привет! обучу за 10 TONcoin или 1500р

Пиши в комментариях что необходимо снять на видео либо описать в статье

Closed

could not initialize WebView #17290

Issue Opened

Kasumiru Opened Issue On Nov 24th 2021, 9:45

Kasumiru

Steps to reproduce

  1. select checkout in telegram channel
  2. press «PAY xxx,xx RUB» button
  3. some second await and I see: «Error: Could not initialize WebView.»

Expected behaviour

open payments web site or paymets window

Actual behaviour

see erorr: «Error: Could not initialize WebView»

Operating system

windows 10 build 19042.1348

Version of Telegram Desktop

3.2.5

Installation source

Static binary from official website

Logs

I can attach full log if it needed.

[2021.11.25 00:42:55] OpenGL: QOpenGLContext created, version: 3.3.
[2021.11.25 00:42:55] OpenGL: [TRUE] (OverlayWidget)
[2021.11.25 00:42:56] Message Info: bad message notification received (error_code 33) for msg_id = 7034255246324421704, seq_no = 42
[2021.11.25 00:42:56] Message Info: bad message notification received, msgId 7034255246324421704, error_code 33
[2021.11.25 00:42:56] API Warning: not loaded minimal channel applied.
[2021.11.25 00:42:56] API Warning: not loaded minimal channel applied.
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.) 

Serge-Mazur

I confirm:
https://i.imgur.com/KxArLA3.png

Tested the ShopBot on my desktop app and if I tick the option Webview then I can not finish my payment.

Version of the desktop app is up to date 3.2.5.

Jackvote

I confirm.
Operating system: windows 7
Version of Telegram Desktop: 3.5.1

The same problem on win10 was solved by an update Microsoft Edge.

On win7, I installed webview2. After that, I installed MS Edge.
The problem has not been fixed.

People can’t use Telegram Bot Payments on Win7

Tested on https://t.me/niloffffbot and others. Different payment systems.

Comment

Kasumiru commented on 11 months ago

Comment

Lp85d commented on 9 months ago

Lp85d

Durger King
Error: Could not initialize WebView.
How to solve the problem?
Telegram Desktop 💕
Версия 3.7 x64 — О программе

IlhomjonMuxtorov

Durger King Error: Could not initialize WebView. How to solve the problem? Telegram Desktop 💕 Версия 3.7 x64 — О программе

I have same problem

OS — Windows 10
Telegram Desktop — 3.7 x64

Comment

Aokromes commented on 9 months ago

Ilya-fedin

Again same problem

Can you take a screenshot of the error?

IlhomjonMuxtorov

Again same problem

Can you take a screenshot of the error?

web_app_wrong web_app_wrong2 My desktop telegram version 3.7.3

Ilya-fedin

My desktop telegram version 3.7.3

Can you provide the logs?

IlhomjonMuxtorov

My desktop telegram version 3.7.3

Can you provide the logs?

[2022.04.30 09:10:21] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)
[2022.04.30 09:11:59] API Warning: not loaded minimal channel applied.
[2022.04.30 09:11:59] API Warning: not loaded minimal channel applied.
[2022.04.30 09:12:16] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)

Ilya-fedin

[2022.04.30 09:10:21] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)

Do you by any chance use some kind of shrunk/modified version of Windows (debloated, despyed, etc)?

Ilya-fedin

You are right, my windows is not offical

That’s most likely the reason. Apparently the service tdesktop uses was ‘debloated’.

Ilya-fedin

@kasumiru can you confirm you use non-offical Windows, too?

IlhomjonMuxtorov

That’s most likely the reason. Apparently the service tdesktop uses was ‘debloated’.

How can I fix it?

Ilya-fedin

How can I fix it?

Well, don’t use shrunk OS

Ilya-fedin

But payment method web view working on my windows

Are you sure? Can you provide a screenshot?

Comment

Lp85d commented on 9 months ago

Lp85d

Ошибка Durger King : не удалось инициализировать WebView. Как решить проблему? Телеграмма для рабочего стола💕 Версия 3.7 x64 — О программа

А всего та надо было установить MicrosoftEdgeWebview2

Ilya-fedin

It’s for Windows 11+. On Windows 8.1-10 tdesktop prefers the built-in Edge engine.

About Repository

kasumiru

could not initialize WebView

Steps to reproduce

  1. select checkout in telegram channel
  2. press «PAY xxx,xx RUB» button
  3. some second await and I see: «Error: Could not initialize WebView.»

Expected behaviour

open payments web site or paymets window

Actual behaviour

see erorr: «Error: Could not initialize WebView»

Operating system

windows 10 build 19042.1348

Version of Telegram Desktop

3.2.5

Installation source

Static binary from official website

Logs

I can attach full log if it needed.

[2021.11.25 00:42:55] OpenGL: QOpenGLContext created, version: 3.3.
[2021.11.25 00:42:55] OpenGL: [TRUE] (OverlayWidget)
[2021.11.25 00:42:56] Message Info: bad message notification received (error_code 33) for msg_id = 7034255246324421704, seq_no = 42
[2021.11.25 00:42:56] Message Info: bad message notification received, msgId 7034255246324421704, error_code 33
[2021.11.25 00:42:56] API Warning: not loaded minimal channel applied.
[2021.11.25 00:42:56] API Warning: not loaded minimal channel applied.
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)
[2021.11.25 00:43:29] WinRT Error: -2147023170 (The remote procedure call failed.)

Serge-Mazur

jackvote

I confirm.
Operating system: windows 7
Version of Telegram Desktop: 3.5.1

The same problem on win10 was solved by an update Microsoft Edge.

On win7, I installed webview2. After that, I installed MS Edge.
The problem has not been fixed.

People can’t use Telegram Bot Payments on Win7

Tested on https://t.me/niloffffbot and others. Different payment systems.

kasumiru

lp85d

Durger King
Error: Could not initialize WebView.
How to solve the problem?
Telegram Desktop 💕
Версия 3.7 x64 — О программе

IlhomjonMuxtorov

Durger King Error: Could not initialize WebView. How to solve the problem? Telegram Desktop 💕 Версия 3.7 x64 — О программе

I have same problem

OS — Windows 10
Telegram Desktop — 3.7 x64

Aokromes

IlhomjonMuxtorov

try 3.7.1

Again same problem

ilya-fedin

Again same problem

Can you take a screenshot of the error?

IlhomjonMuxtorov

Again same problem

Can you take a screenshot of the error?

web_app_wrong
web_app_wrong2
My desktop telegram version 3.7.3

ilya-fedin

My desktop telegram version 3.7.3

Can you provide the logs?

IlhomjonMuxtorov

My desktop telegram version 3.7.3

Can you provide the logs?

[2022.04.30 09:10:21] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)
[2022.04.30 09:11:59] API Warning: not loaded minimal channel applied.
[2022.04.30 09:11:59] API Warning: not loaded minimal channel applied.
[2022.04.30 09:12:16] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)

ilya-fedin

[2022.04.30 09:10:21] WinRT Error: -2147023170 (Сбой при удаленном вызове процедуры.)

Do you by any chance use some kind of shrunk/modified version of Windows (debloated, despyed, etc)?

IlhomjonMuxtorov

You are right, my windows is not offical

ilya-fedin

You are right, my windows is not offical

That’s most likely the reason. Apparently the service tdesktop uses was ‘debloated’.

IlhomjonMuxtorov

Web view working on offical windows

ilya-fedin

@kasumiru can you confirm you use non-offical Windows, too?

IlhomjonMuxtorov

That’s most likely the reason. Apparently the service tdesktop uses was ‘debloated’.

How can I fix it?

ilya-fedin

How can I fix it?

Well, don’t use shrunk OS

IlhomjonMuxtorov

IlhomjonMuxtorov

But payment method web view working on my windows

Grepper Logo

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
June 22, 2022

Popularity
2/10

Helpfulness
8/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • telegram desktop error could not initialize webview
  • Related Problems

  • telegram desktop error could not initialize webview
  • TPC Matrix View Full Screen

    telegram desktop error could not initialize webview

    Comment

    2


    Popularity

    2/10 Helpfulness
    8/10
    Language
    whatever

    Source: msedge.sf.dl.delivery.mp.microsoft.com

    Tags: desktop
    telegram
    webview
    whatever

    Shadow

    Contributed on Jun 22 2022

    Shadow

    1,030 Answers  Avg Quality 8/10


    Grepper

    Features
    Reviews
    Code Answers
    Search Code Snippets

    Plans & Pricing
    FAQ
    Welcome
    Browsers Supported
    Grepper Teams

    Documentation

    Adding a Code Snippet

    Viewing & Copying Snippets

    Social

    Twitter LogoTwitter

    LinkedIn LogoLinkedIn

    Legal

    Privacy Policy
    Terms

    Contact

    support@codegrepper.com

    WebView с Telegram Desktop. А с телефона все работает нормально. Хотя Durger King и с десктопной версии работает хорошо.
    Подскажите, в какую сторону копать? (Где-то выше писали про TLS — используется версия 1.2)

    russian

    programming

    aiogram


    12

    ответов

    🤔Это же баг телеги, который пока ещё не исправили, у меня телега ваще просто вылетает, так не должно быть, разрабы телеги пока всё ещё что-то исправляют

    У меня тоже ток на андроиде пашет, просто там разные программисты сидят, так что пока ещё можно не торопиться с обновой, её нормально везде не разглядеть

    Нет, просто при нажатии на кнопку ничего не происходит. Но это на Mac


    Alexey

    Нет, просто при нажатии на кнопку ничего не происх…

    Запрос отправляется на сервер при нажатии на кнопку?

    Я о маке. Отправляется ли запрос на получение статики от сервера при нажатии на кнопку на маке?


    Alexey

    Это через debug mode можно посмотреть?

    В случае с моим примером — просто будет вывод в терминал что была попытка получить статику и статус успешности


    Alexey

    Я разберусь и отпишу

    Мой пример пробовал открывать?

    (Бот имеется ввиду)


    ༼AndrewKing༽ 🇺🇦 [Робокотокот]

    Мой пример пробовал открывать?

    (Бот имеется ввиду…

    Если речь про @webAppOrderFood_bot, то да, пробовал, такое же поведение

    +

    1

    -

    3

    28.08.2016, 17:59

    Судя по приведённым Вами сообщениям, возникла какая-то проблема с файлом лога. Попробуйте для начала обновить или переустановить программу. Также проверьте, всё ли в порядке с интернетом. Попробуйте альтернативный вариант подключения к интернету (если подключены по wi-fi, то подключитесь к 3G/LTE, и наоборот).

    +

    6

    -

    2

    03.08.2017, 12:53

    удалите в корневой папке файлы log_start 1-2-3-4-5-6 и попробуйте запустить программы

    +

    8

    -

    1

    06.09.2018, 10:58

    1) В папке с программой удалите файлы типа log_start 1,2 и т.д.
    2) Закройте все процессы через диспетчер приложений alt+ctrl+del.
    3) Запустите программу, ждите.

    +

    0

    -

    0

    31.01.2020, 05:26

    2020.01.31 09:47:24] Executable path before check: C:/Users/Nirmala/AppData/Roaming/Telegram Desktop/Telegram.exe у меня телеграмм на ноутбуке установлен.сегодня не открывается и пришёл такое уведомление.что это значит?

    +

    0

    -

    0

    08.02.2020, 15:19

    Здравствуйте, у вас вероятно проблема с правами доступа к рабочей папке вашего телеграма, попробуйте запустить телеграм с правами администратора, если это исправит проблему, то измените права доступа к указаной в логе workdir, на любой доступ для всех юзеров

    +

    0

    -

    0

    21.09.2020, 18:50

    Добрый день пре запуске телеграмма мне пишет иот это: : C:/Users/38097/AppData/Roaming/Telegram Desktop/Telegram.exe

    +

    5

    -

    0

    07.11.2020, 10:17

    [2020.11.07 12:15:13] Executable path before check: C:/Users/User/AppData/Roaming/Telegram Desktop/Telegram.exe
    [2020.11.07 12:15:13] FATAL: Could not move logging to ‘C:/Users/User/AppData/Roaming/Telegram Desktop/log.txt’!
    пишет это,что делать?

    +

    0

    -

    0

    27.02.2021, 09:54

    удалите в корневой папке файлы log_start 1-2-3-4-5-6 и попробуйте запустить программы

    спасибо, помогло

    В ответ на сообщение от Боря
    #179344      

    +

    3

    -

    3

    22.03.2021, 07:39

    Попробуйте установить телеграм на другой диск, не благодарите)

    +

    0

    -

    0

    19.04.2021, 08:22

    Благодарю, за совет. Это помогло. Но я так и не смогла найти корневую папку. установила в другое место.

    +

    0

    -

    0

    19.06.2021, 10:41

    Я нашел такой ответ в интернете.

    Все очень просто делается:
    1. Перезапуск ПК
    2. После перезапуска НЕ ЗАПУСКАЙТЕ ПРОГРАММУ!
    3. После перезапуска заходим там где Telegram: C:UsersАдминистраторAppDataRoamingTelegram Desktop
    4. Удаляем все .txt файлы которые примерно называются как: log, log_start0 и т. д

    Если не помогло то:
    1. Скачиваем программу Unlocker 1.9.2 (Она бесплатная скачивал с сайта softportal)
    (или любую программу которая может удалить файл который вы обозначите, например Reg Organizer или Revo Uninstaller Pro, но лучше всего тут подойдет программа Unlocker)
    2. После установки перезапускаем ПК
    3. После перезапуска заходим там где Telegram:C:UsersАдминистраторAppDataRoamingTelegram Desktop
    4. Нажимаем правой кнопкой мыши по файлу log.txt ищем Unlocker
    5. Нажимаем на Unlocker, вам высветилось окно
    6. Нажимаем на «Нет действия» выбираем «Удалить» после чего нажимаем «ОК»
    7. Вам вылезет Ошибка: Удаление объекта невозможно Выполнить удаление при следующей загрузке системы?
    8. Нажимаем ДА!
    9. Перезапускаем ПК и радуемся!

    И мой совет на будущее, при каждом запуске ПК проверяйте всегда теперь, создался ли у вас log.txt или нет,
    Если опять создался то удаляем спокойно а не паримся с перезагрузкой все время, после чего только запускам программу Telegram.

    +

    0

    -

    0

    16.07.2021, 07:15

    Добрый день. После обновления Телеграмм стал выдавать ошибку (скрин ниже). После удаления и переустановки все так же. Помогите, пожалуйста!!!

    +

    0

    -

    0

    16.07.2021, 08:51

    Елена

    Добрый день. После обновления Телеграмм стал выдавать ошибку (скрин ниже). После удаления и переустановки все так же. Помогите, пожалуйста!!!

    Похоже сегодня подобный сбой у многих. После обновления действительно ничем не лечится ошибка, только установка прошло версии

    В ответ на сообщение от Елена
    #222612      

    +

    0

    -

    0

    16.07.2021, 08:53

    Елена

    Добрый день. После обновления Телеграмм стал выдавать ошибку (скрин ниже). После удаления и переустановки все так же. Помогите, пожалуйста!!!

    Точно так же, обновление возможно плохое какое-то)

    В ответ на сообщение от Елена
    #222612      

    +

    0

    -

    0

    16.07.2021, 14:36

    Дайте ссылку для нормальной загрузки Телеграм

    полное удаление и установка ничего не дало

    +

    0

    -

    0

    17.07.2021, 08:02

    Гость

    Дайте ссылку для нормальной загрузки Телеграм

    полное удаление и установка ничего не дало

    Вроде исправили ошибку. По крайней мере сегодня утром обновился без проблем

    В ответ на сообщение от Гость
    #222624      

    +

    0

    -

    0

    17.07.2021, 10:56

    Елена

    Добрый день. После обновления Телеграмм стал выдавать ошибку (скрин ниже). После удаления и переустановки все так же. Помогите, пожалуйста!!!

    Сегодня удалось обновить без ошибок) Похоже, что оперативно исправили глюк)

    В ответ на сообщение от Елена
    #222612      

    +

    0

    -

    0

    17.09.2021, 03:47

    Маты, сообщения БОЛЬШИМИ БУКВАМИ, с грубыми ошибками, просто глупые и совершенно не по теме будут удаляться.

    Спасибо, что Вы с нами

    +

    1

    -

    0

    15.03.2022, 13:25

    Я удалил log.txt и все заработало

    Telegram bots can completely replace any website. They support seamless authorization, integrated payments via 15 payment providers (with Google Pay and Apple Pay out of the box), delivering tailored push notifications to users, and much more.

    With Web Apps, bots get a whole new dimension. Bot developers can create infinitely flexible interfaces with JavaScript, the most widely used programming language in the world.

    To see a Web App in action, try our sample @DurgerKingBot.


    Recent changes

    December 30, 2022

    Bot API 6.4

    • Added the field platform, the optional parameter options to the method openLink and the methods showScanQrPopup, closeScanQrPopup, readTextFromClipboard to the class WebApp.
    • Added the events qrTextReceived, clipboardTextReceived.

    August 12, 2022

    Bot API 6.2

    • Added the field isClosingConfirmationEnabled and the methods enableClosingConfirmation, disableClosingConfirmation, showPopup, showAlert, showConfirm to the class WebApp.
    • Added the field is_premium to the class WebAppUser.
    • Added the event popupClosed.

    June 20, 2022

    Bot API 6.1

    • Added the ability to use bots added to the attachment menu in group, supergroup and channel chats.
    • Added support for t.me links that can be used to select the chat in which the attachment menu with the bot will be opened.
    • Added the fields version, headerColor, backgroundColor, BackButton, HapticFeedback and the methods isVersionAtLeast, setHeaderColor, setBackgroundColor, openLink, openTelegramLink, openInvoice to the class WebApp.
    • Added the field secondary_bg_color to the class ThemeParams.
    • Added the method offClick to the class MainButton.
    • Added the fields chat, can_send_after to the class WebAppInitData.
    • Added the events backButtonClicked, settingsButtonClicked, invoiceClosed.

    Designing Web Apps

    Color Schemes

    Web Apps always receive data about the user’s current color theme in real time, so you can adjust the appearance of your interfaces to match it. For example, when users switch between Day and Night modes or use various custom themes.

    Jump to technical information

    Design Guidelines

    Telegram apps are known for being snappy, smooth and following a consistent cross-platform design. Your Web App should ideally reflect these principles.

    • All elements should be responsive and designed with a mobile-first approach.
    • Interactive elements should mimic the style, behavior and intent of UI components that already exist.
    • All included animations should be smooth, ideally 60fps.
    • All inputs and images should contain labels for accessibility purposes.
    • The app should deliver a seamless experience by monitoring the dynamic theme-based colors provided by the API and using them accordingly.

    Implementing Web Apps

    Telegram currently supports four different ways of launching Web Apps: from a keyboard button, from an inline button, from the bot menu button – and even from the attachment menu.

    Types of buttons

    Keyboard Button Web Apps

    TL;DR: Web Apps launched from a web_app type keyboard button can send data back to the bot in a service message using Telegram.WebApp.sendData. This makes it possible for the bot to produce a response without communicating with any external servers.

    Users can interact with bots using custom keyboards, buttons under bot messages, as well as by sending freeform text messages or any of the attachment types supported by Telegram: photos and videos, files, locations, contacts and polls. For even more flexibility, bots can utilize the full power of HTML5 to create user-friendly input interfaces.

    You can send a web_app type KeyboardButton that opens a Web App from the specified URL.

    To transmit data from the user back to the bot, the Web App can call the Telegram.WebApp.sendData method. Data will be transmitted to the bot as a String in a service message. The bot can continue communicating with the user after receiving it.

    Good for:

    • Сustom data input interfaces (a personalized calendar for selecting dates; selecting data from a list with advanced search options; a randomizer that lets the user “spin a wheel” and chooses one of the available options, etc.)
    • Reusable components that do not depend on a particular bot.

    Inline Button Web Apps

    TL;DR: For more interactive Web Apps like @DurgerKingBot, use a web_app type Inline KeyboardButton, which gets basic user information and can be used to send a message on behalf of the user to the chat with the bot.

    If receiving text data alone is insufficient or you need a more advanced and personalized interface, you can open a Web App using a web_app type Inline KeyboardButton.

    From the button, a Web App will open with the URL specified in the button. In addition to the user’s theme settings, it will receive basic user information (ID, name, username, language_code) and a unique identifier for the session, query_id, which allows messages on behalf of the user to be sent back to the bot.

    The bot can call the Bot API method answerWebAppQuery to send an inline message from the user back to the bot and close the Web App. After receiving the message, the bot can continue communicating with the user.

    Good for:

    • Fully-fledged web services and integrations of any kind.
    • The use cases are effectively unlimited.

    Launching Web Apps from the Menu Button

    TL;DR: Web Apps can be launched from a customized menu button. This simply offers a quicker way to access the app and is otherwise identical to launching a Web App from an inline button.

    By default, chats with bots always show a convenient menu button that provides quick access to all listed commands. With Bot API 6.0, this button can be used to launch a Web App instead.

    To configure the menu button, you must specify the text it should show and the Web App URL. There are two ways to set these parameters:

    • To customize the button for all users, use @BotFather (the /setmenubutton command or Bot Settings > Menu Button).
    • To customize the button for both all users and specific users, use the setChatMenuButton method in the Bot API. For example, change the button text according to the user’s language, or show links to different Web Apps based on a user’s settings in your bot.

    Apart from this, Web Apps opened via the menu button work in the exact same way as when using inline buttons.

    @DurgerKingBot allows launching its Web App both from an inline button and from the menu button.

    Launching Web Apps from the Attachment Menu

    TL;DR: Web App Bots can request to be added directly to a user’s attachment menu, allowing them to be quickly launched from any chat. To try this mode, open this attachment menu link for @DurgerKingBot, then use the Attach menu in any type of chat.

    Web App Bots can request to be added directly to a user’s attachment menu, allowing them to be quickly launched from any type of chat. You can configure in which types of chats your web app can be started from the attachment menu (private, groups, supergroups or channels).

    Attachment menu integration is currently only available for major advertisers on the Telegram Ad Platform. However, all bots can use it in the test server environment.

    To enable this feature for your bot, open @BotFather from an account on the test server and send the /setattach command – or go to Bot Settings > Configure Attachment Menu. Then specify the URL that will be opened to launch the bot’s Web App via its icon in the attachment menu.

    You can add a ‘Settings’ item to the context menu of your Web App using @BotFather. When users select this option from the menu, your bot will receive a settingsButtonClicked event.

    In addition to the user’s theme settings, the bot will receive basic user information (ID, name, username, language_code, photo), as well as public info about the chat partner (ID, name, username, photo) or the chat info (ID, type, title, username, photo) and a unique identifier for the web view session query_id, which allows messages of any type to be sent to the chat on behalf of the user that opened the bot.

    The bot can call the Bot API method answerWebAppQuery, which sends an inline message from the user via the bot to the chat where it was launched and closes the Web App.

    You can read more about adding bots to the attachment menu here.


    Initializing Web Apps

    To connect your Web App to the Telegram client, place the script telegram-web-app.js in the <head> tag before any other scripts, using this code:

    <script src="https://telegram.org/js/telegram-web-app.js"></script>

    Once the script is connected, a window.Telegram.WebApp object will become available with the following fields:

    Field Type Description
    initData String A string with raw data transferred to the Web App, convenient for validating data.
    WARNING: Validate data from this field before using it on the bot’s server.
    initDataUnsafe WebAppInitData An object with input data transferred to the Web App.
    WARNING: Data from this field should not be trusted. You should only use data from initData on the bot’s server and only after it has been validated.
    version String The version of the Bot API available in the user’s Telegram app.
    platform NEW String The name of the platform of the user’s Telegram app.
    colorScheme String The color scheme currently used in the Telegram app. Either “light” or “dark”.
    Also available as the CSS variable var(--tg-color-scheme).
    themeParams ThemeParams An object containing the current theme settings used in the Telegram app.
    isExpanded Boolean True, if the Web App is expanded to the maximum available height. False, if the Web App occupies part of the screen and can be expanded to the full height using the expand() method.
    viewportHeight Float The current height of the visible area of the Web App. Also available in CSS as the variable var(--tg-viewport-height).

    The application can display just the top part of the Web App, with its lower part remaining outside the screen area. From this position, the user can “pull” the Web App to its maximum height, while the bot can do the same by calling the expand() method. As the position of the Web App changes, the current height value of the visible area will be updated in real time.

    Please note that the refresh rate of this value is not sufficient to smoothly follow the lower border of the window. It should not be used to pin interface elements to the bottom of the visible area. It’s more appropriate to use the value of the viewportStableHeight field for this purpose.

    viewportStableHeight Float The height of the visible area of the Web App in its last stable state. Also available in CSS as a variable var(--tg-viewport-stable-height).

    The application can display just the top part of the Web App, with its lower part remaining outside the screen area. From this position, the user can “pull” the Web App to its maximum height, while the bot can do the same by calling the expand() method. Unlike the value of viewportHeight, the value of viewportStableHeight does not change as the position of the Web App changes with user gestures or during animations. The value of viewportStableHeight will be updated after all gestures and animations are completed and the Web App reaches its final size.

    Note the event viewportChanged with the passed parameter isStateStable=true, which will allow you to track when the stable state of the height of the visible area changes.

    headerColor String Current header color in the #RRGGBB format.
    backgroundColor String Current background color in the #RRGGBB format.
    isClosingConfirmationEnabled Boolean True, if the confirmation dialog is enabled while the user is trying to close the Web App. False, if the confirmation dialog is disabled.
    BackButton BackButton An object for controlling the back button which can be displayed in the header of the Web App in the Telegram interface.
    MainButton MainButton An object for controlling the main button, which is displayed at the bottom of the Web App in the Telegram interface.
    HapticFeedback HapticFeedback An object for controlling haptic feedback.
    isVersionAtLeast(version) Function Returns true if the user’s app supports a version of the Bot API that is equal to or higher than the version passed as the parameter.
    setHeaderColor(color) Function Bot API 6.1+ A method that sets the app header color. You can only pass Telegram.WebApp.themeParams.bg_color or Telegram.WebApp.themeParams.secondary_bg_color as a color or you can use keywords bg_color, secondary_bg_color instead.
    setBackgroundColor(color) Function Bot API 6.1+ A method that sets the app background color in the #RRGGBB format or you can use keywords bg_color, secondary_bg_color instead.
    enableClosingConfirmation() Function Bot API 6.2+ A method that enables a confirmation dialog while the user is trying to close the Web App.
    disableClosingConfirmation() Function Bot API 6.2+ A method that disables the confirmation dialog while the user is trying to close the Web App.
    onEvent(eventType, eventHandler) Function A method that sets the app event handler. Check the list of available events.
    offEvent(eventType, eventHandler) Function A method that deletes a previously set event handler.
    sendData(data) Function A method used to send data to the bot. When this method is called, a service message is sent to the bot containing the data data of the length up to 4096 bytes, and the Web App is closed. See the field web_app_data in the class Message.

    This method is only available for Web Apps launched via a Keyboard button.

    openLink(url[, options]) Function A method that opens a link in an external browser. The Web App will not be closed.
    Bot API 6.4+ If the optional options parameter is passed with the field try_instant_view=true, the link will be opened in Instant View mode if possible.

    Note that this method can be called only in response to user interaction with the Web App interface (e.g. a click inside the Web App or on the main button)

    openTelegramLink(url) Function A method that opens a telegram link inside Telegram app. The Web App will be closed.
    openInvoice(url[, callback]) Function Bot API 6.1+ A method that opens an invoice using the link url. The Web App will receive the event invoiceClosed when the invoice is closed. If an optional callback parameter was passed, the callback function will be called and the invoice status will be passed as the first argument.
    showPopup(params[, callback]) Function Bot API 6.2+ A method that shows a native popup described by the params argument of the type PopupParams. The Web App will receive the event popupClosed when the popup is closed. If an optional callback parameter was passed, the callback function will be called and the field id of the pressed button will be passed as the first argument.
    showAlert(message[, callback]) Function Bot API 6.2+ A method that shows message in a simple alert with a ‘Close’ button. If an optional callback parameter was passed, the callback function will be called when the popup is closed.
    showConfirm(message[, callback]) Function Bot API 6.2+ A method that shows message in a simple confirmation window with ‘OK’ and ‘Cancel’ buttons. If an optional callback parameter was passed, the callback function will be called when the popup is closed and the first argument will be a boolean indicating whether the user pressed the ‘OK’ button.
    showScanQrPopup(params[, callback]) NEW Function Bot API 6.4+ A method that shows a native popup for scanning a QR code described by the params argument of the type ScanQrPopupParams. The Web App will receive the event qrTextReceived every time the scanner catches a code with text data. If an optional callback parameter was passed, the callback function will be called and the text from the QR code will be passed as the first argument. Returning true inside this callback function causes the popup to be closed.
    closeScanQrPopup() NEW Function Bot API 6.4+ A method that closes the native popup for scanning a QR code opened with the showScanQrPopup method. Run it if you received valid data in the event qrTextReceived.
    readTextFromClipboard([callback]) NEW Function Bot API 6.4+ A method that requests text from the clipboard. The Web App will receive the event clipboardTextReceived. If an optional callback parameter was passed, the callback function will be called and the text from the clipboard will be passed as the first argument.

    Note: this method can be called only for Web Apps launched from the attachment menu and only in response to a user interaction with the Web App interface (e.g. a click inside the Web App or on the main button).

    ready() Function A method that informs the Telegram app that the Web App is ready to be displayed.
    It is recommended to call this method as early as possible, as soon as all essential interface elements are loaded. Once this method is called, the loading placeholder is hidden and the Web App is shown.
    If the method is not called, the placeholder will be hidden only when the page is fully loaded.
    expand() Function A method that expands the Web App to the maximum available height. To find out if the Web App is expanded to the maximum height, refer to the value of the Telegram.WebApp.isExpanded parameter
    close() Function A method that closes the Web App.

    ThemeParams

    Web Apps can adjust the appearance of the interface to match the Telegram user’s app in real time. This object contains the user’s current theme settings:

    Field Type Description
    bg_color String Optional. Background color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-bg-color).
    text_color String Optional. Main text color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-text-color).
    hint_color String Optional. Hint text color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-hint-color).
    link_color String Optional. Link color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-link-color).
    button_color String Optional. Button color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-button-color).
    button_text_color String Optional. Button text color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-button-text-color).
    secondary_bg_color String Optional. Bot API 6.1+ Secondary background color in the #RRGGBB format.
    Also available as the CSS variable var(--tg-theme-secondary-bg-color).

    PopupParams

    This object describes the native popup.

    Field Type Description
    title String Optional. The text to be displayed in the popup title, 0-64 characters.
    message String The message to be displayed in the body of the popup, 1-256 characters.
    buttons Array of PopupButton Optional. List of buttons to be displayed in the popup, 1-3 buttons. Set to [{“type”:“close”}] by default.

    ScanQrPopupParams

    NEW This object describes the native popup for scanning QR codes.

    Field Type Description
    text String Optional. The text to be displayed under the ‘Scan QR’ heading, 0-64 characters.

    PopupButton

    This object describes the native popup button.

    Field Type Description
    id String Optional. Identifier of the button, 0-64 characters. Set to empty string by default.
    If the button is pressed, its id is returned in the callback and the popupClosed event.
    type String Optional. Type of the button. Set to default by default.
    Can be one of these values:
    default, a button with the default style,
    ok, a button with the localized text “OK”,
    close, a button with the localized text “Close”,
    cancel, a button with the localized text “Cancel”,
    destructive, a button with a style that indicates a destructive action (e.g. “Remove”, “Delete”, etc.).
    text String Optional. The text to be displayed on the button, 0-64 characters. Required if type is default or destructive. Irrelevant for other types.

    BackButton

    This object controls the back button, which can be displayed in the header of the Web App in the Telegram interface.

    Field Type Description
    isVisible Boolean Shows whether the button is visible. Set to false by default.
    onClick(callback) Function Bot API 6.1+ A method that sets the button press event handler. An alias for Telegram.WebApp.onEvent('backButtonClicked', callback)
    offClick(callback) Function Bot API 6.1+ A method that removes the button press event handler. An alias for Telegram.WebApp.offEvent('backButtonClicked', callback)
    show() Function Bot API 6.1+ A method to make the button active and visible.
    hide() Function Bot API 6.1+ A method to hide the button.

    All these methods return the BackButton object so they can be chained.

    MainButton

    This object controls the main button, which is displayed at the bottom of the Web App in the Telegram interface.

    Field Type Description
    text String Current button text. Set to CONTINUE by default.
    color String Current button color. Set to themeParams.button_color by default.
    textColor String Current button text color. Set to themeParams.button_text_color by default.
    isVisible Boolean Shows whether the button is visible. Set to false by default.
    isActive Boolean Shows whether the button is active. Set to true by default.
    isProgressVisible Boolean Readonly. Shows whether the button is displaying a loading indicator.
    setText(text) Function A method to set the button text.
    onClick(callback) Function A method that sets the button press event handler. An alias for Telegram.WebApp.onEvent('mainButtonClicked', callback)
    offClick(callback) Function A method that removes the button press event handler. An alias for Telegram.WebApp.offEvent('mainButtonClicked', callback)
    show() Function A method to make the button visible.
    Note that opening the Web App from the attachment menu hides the main button until the user interacts with the Web App interface.
    hide() Function A method to hide the button.
    enable() Function A method to enable the button.
    disable() Function A method to disable the button.
    showProgress(leaveActive) Function A method to show a loading indicator on the button.
    It is recommended to display loading progress if the action tied to the button may take a long time. By default, the button is disabled while the action is in progress. If the parameter leaveActive=true is passed, the button remains enabled.
    hideProgress() Function A method to hide the loading indicator.
    setParams(params) Function A method to set the button parameters. The params parameter is an object containing one or several fields that need to be changed:
    text — button text;
    color — button color;
    text_color — button text color;
    is_active — enable the button;
    is_visible — show the button.

    All these methods return the MainButton object so they can be chained.

    HapticFeedback

    This object controls haptic feedback.

    Field Type Description
    impactOccurred(style) Function Bot API 6.1+ A method tells that an impact occurred. The Telegram app may play the appropriate haptics based on style value passed. Style can be one of these values:
    light, indicates a collision between small or lightweight UI objects,
    medium, indicates a collision between medium-sized or medium-weight UI objects,
    heavy, indicates a collision between large or heavyweight UI objects,
    rigid, indicates a collision between hard or inflexible UI objects,
    soft, indicates a collision between soft or flexible UI objects.
    notificationOccurred(type) Function Bot API 6.1+ A method tells that a task or action has succeeded, failed, or produced a warning. The Telegram app may play the appropriate haptics based on type value passed. Type can be one of these values:
    error, indicates that a task or action has failed,
    success, indicates that a task or action has completed successfully,
    warning, indicates that a task or action produced a warning.
    selectionChanged() Function Bot API 6.1+ A method tells that the user has changed a selection. The Telegram app may play the appropriate haptics.

    Do not use this feedback when the user makes or confirms a selection; use it only when the selection changes.

    All these methods return the HapticFeedback object so they can be chained.

    WebAppInitData

    This object contains data that is transferred to the Web App when it is opened. It is empty if the Web App was launched from a keyboard button.

    Field Type Description
    query_id String Optional. A unique identifier for the Web App session, required for sending messages via the answerWebAppQuery method.
    user WebAppUser Optional. An object containing data about the current user.
    receiver WebAppUser Optional. An object containing data about the chat partner of the current user in the chat where the bot was launched via the attachment menu. Returned only for private chats and only for Web Apps launched via the attachment menu.
    chat WebAppChat Optional. An object containing data about the chat where the bot was launched via the attachment menu. Returned for supergroups, channels and group chats – only for Web Apps launched via the attachment menu.
    start_param String Optional. The value of the startattach parameter, passed via link. Only returned for Web Apps when launched from the attachment menu via link.

    The value of the start_param parameter will also be passed in the GET-parameter tgWebAppStartParam, so the Web App can load the correct interface right away.

    can_send_after Integer Optional. Time in seconds, after which a message can be sent via the answerWebAppQuery method.
    auth_date Integer Unix time when the form was opened.
    hash String A hash of all passed parameters, which the bot server can use to check their validity.

    WebAppUser

    This object contains the data of the Web App user.

    Field Type Description
    id Integer A unique identifier for the user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. It has at most 52 significant bits, so a 64-bit integer or a double-precision float type is safe for storing this identifier.
    is_bot Boolean Optional. True, if this user is a bot. Returns in the receiver field only.
    first_name String First name of the user or bot.
    last_name String Optional. Last name of the user or bot.
    username String Optional. Username of the user or bot.
    language_code String Optional. IETF language tag of the user’s language. Returns in user field only.
    is_premium True Optional. True, if this user is a Telegram Premium user
    photo_url String Optional. URL of the user’s profile photo. The photo can be in .jpeg or .svg formats. Only returned for Web Apps launched from the attachment menu.

    WebAppChat

    This object represents a chat.

    Field Type Description
    id Integer Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.
    type String Type of chat, can be either “group”, “supergroup” or “channel”
    title String Title of the chat
    username String Optional. Username of the chat
    photo_url String Optional. URL of the chat’s photo. The photo can be in .jpeg or .svg formats. Only returned for Web Apps launched from the attachment menu.

    Validating data received via the Web App

    To validate data received via the Web App, one should send the data from the Telegram.WebApp.initData field to the bot’s backend. The data is a query string, which is composed of a series of field-value pairs.

    You can verify the integrity of the data received by comparing the received hash parameter with the hexadecimal representation of the HMAC-SHA-256 signature of the data-check-string with the secret key, which is the HMAC-SHA-256 signature of the bot’s token with the constant string WebAppData used as a key.

    Data-check-string is a chain of all received fields, sorted alphabetically, in the format key=<value> with a line feed character (‘n’, 0x0A) used as separator – e.g., 'auth_date=<auth_date>nquery_id=<query_id>nuser=<user>'.

    The full check might look like:

    data_check_string = ...
    secret_key = HMAC_SHA256(<bot_token>, "WebAppData")
    if (hex(HMAC_SHA256(data_check_string, secret_key)) == hash) {
      // data is from Telegram
    }

    To prevent the use of outdated data, you can additionally check the auth_date field, which contains a Unix timestamp of when it was received by the Web App.

    Once validated, the data may be used on your server. Complex data types are represented as JSON-serialized objects.

    Events Available for Web Apps

    The Web App can receive events from the Telegram app, onto which a handler can be attached using the Telegram.WebApp.onEvent(eventType, eventHandler) method. Inside eventHandler the this object refers to Telegram.WebApp, the set of parameters sent to the handler depends on the event type. Below is a list of possible events:

    eventType Description
    themeChanged Occurs whenever theme settings are changed in the user’s Telegram app (including switching to night mode).
    eventHandler receives no parameters, new theme settings and color scheme can be received via this.themeParams and this.colorScheme respectively.
    viewportChanged Occurs when the visible section of the Web App is changed.
    eventHandler receives an object with the single field isStateStable. If isStateStable is true, the resizing of the Web App is finished. If it is false, the resizing is ongoing (the user is expanding or collapsing the Web App or an animated object is playing). The current value of the visible section’s height is available in this.viewportHeight.
    mainButtonClicked Occurs when the main button is pressed.
    eventHandler receives no parameters.
    backButtonClicked Bot API 6.1+ Occurrs when the back button is pressed.
    eventHandler receives no parameters.
    settingsButtonClicked Bot API 6.1+ Occurrs when the Settings item in context menu is pressed.
    eventHandler receives no parameters.
    invoiceClosed Bot API 6.1+ Occurrs when the opened invoice is closed.
    eventHandler receives an object with the two fields: url – invoice link provided and status – one of the invoice statuses:
    paid – invoice was paid successfully,
    cancelled – user closed this invoice without paying,
    failed – user tried to pay, but the payment was failed,
    pending – the payment is still processing. The bot will receive a service message about a successful payment when the payment is successfully paid.
    popupClosed Bot API 6.2+ Occurrs when the opened popup is closed.
    eventHandler receives an object with the single field button_id – the value of the field id of the pressed button. If no buttons were pressed, the field button_id will be null.
    qrTextReceived NEW Bot API 6.4+ Occurs when the QR code scanner catches a code with text data.
    eventHandler receives an object with the single field data containing text data from the QR code.
    clipboardTextReceived NEW Bot API 6.4+ Occurrs when the readTextFromClipboard method is called.
    eventHandler receives an object with the single field data containing text data from the clipboard. If the clipboard contains non-text data, the field data will be an empty string. If the Web App has no access to the clipboard, the field data will be null.

    Adding Bots to the Attachment Menu

    Attachment menu integration is currently only available for major advertisers on the Telegram Ad Platform. However, all bots can use it in the test server environment. Talk to Botfather on the test server to set up the integration.

    A special link is used to add bots to the attachment menu:

    https://t.me/botusername?startattach
    or
    https://t.me/botusername?startattach=command

    For example, open this attachment menu link for @DurgerKingBot, then use the Attach menu in any private chat.

    Opening the link prompts the user to add the bot to their attachment menu. If the bot has already been added, the attachment menu will open in the current chat and redirect to the bot there (if the link is opened from a 1-on-1 chat). If a non-empty startattach parameter was included in the link, it will be passed to the Web App in the start_param field and in the GET parameter tgWebAppStartParam.

    The following link formats are also supported:

    https://t.me/username?attach=botusername
    https://t.me/username?attach=botusername&startattach=command
    https://t.me/+1234567890?attach=botusername
    https://t.me/+1234567890?attach=botusername&startattach=command

    These links open the Web App in the attachment menu in the chat with a specific user. If the bot wasn’t already added to the attachment menu, the user will be prompted to do so. If a non-empty startattach parameter was included in the link, it will be passed to the Web App in the start_param field and in the GET parameter tgWebAppStartParam.

    Bot API 6.1+ supports a new link format:

    https://t.me/botusername?startattach&choose=users+bots
    https://t.me/botusername?startattach=command&choose=groups+channels

    Opening such a link prompts the user to choose a specific chat and opens the attachment menu in that chat. If the bot wasn’t already added to the attachment menu, the user will be prompted to do so. You can specify which types of chats the user will be able to choose from. It can be one or more of the following types: users, bots, groups, channels separated by a + sign. If a non-empty startattach parameter was included in the link, it will be passed to the Web App in the start_param field and in the GET parameter tgWebAppStartParam.

    Testing Web Apps

    Using bots in the test environment

    To log in to the test environment, use either of the following:

    • iOS: tap 10 times on the Settings icon > Accounts > Login to another account > Test.
    • Telegram Desktop: open ☰ Settings > Shift + Alt + Right click ‘Add Account’ and select ‘Test Server’.
    • macOS: click the Settings icon 10 times to open the Debug Menu, ⌘ + click ‘Add Account’ and log in via phone number.

    The test environment is completely separate from the main environment, so you will need to create a new user account and a new bot with @BotFather.

    After receiving your bot token, you can send requests to the Bot API in this format:

    https://api.telegram.org/bot<token>/test/METHOD_NAME

    Note: When working with the test environment, you may use HTTP links without TLS to test your Web App.

    Debug Mode for Web Apps

    Use these tools to find app-specific issues in your Web App:

    Android

    • Enable USB-Debugging on your device.
    • In Telegram Settings, scroll all the way down, press and hold on the version number two times.
    • Choose Enable WebView Debug in the Debug Settings.
    • Connect your phone to your computer and open chrome://inspect/#devices in Chrome – you will see your Web App there when you launch it on your phone.

    Telegram Desktop on Windows and Linux

    • Download and launch the Beta Version of Telegram Desktop on Windows or Linux (not supported on Telegram Desktop for macOS yet).
    • Go to Settings > Advanced > Experimental settings > Enable webview inspection.
    • Right click in the WebView and choose Inspect.

    Telegram macOS

    • Download and launch the Beta Version of Telegram macOS.
    • Quickly click 5 times on the Settings icon to open the debug menu and enable “Debug Web Apps”.
    • Right click in the web app and choose Inspect Element.

    When ever I try to use a web view it gives me a null pointer exception, my code:

    import android.app.Activity;
    import android.os.Bundle;
    import android.webkit.WebChromeClient;
    import android.webkit.WebView;
    
    public class Main extends Activity {
        WebView webView;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            webView = (WebView)findViewById(R.id.webView);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setWebChromeClient(new WebChromeClient());
            webView.loadUrl("file:///android_asset/www/index.html");
        }
    }
    

    the Logs are:

    02-18 22:08:06.224: ERROR/AndroidRuntime(355): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.web/com.test.web.Main}: java.lang.NullPointerException
    02-18 22:08:06.224: ERROR/AndroidRuntime(355): Caused by: java.lang.NullPointerException
    02-18 22:08:06.224: ERROR/AndroidRuntime(355): at com.test.web.Main.onCreate(Main.java:17)

    (there where more logs just none of them pertained to the problem)

    On a semi- related note how do you make code look like code on stackexchange?

    So I’m guessing the webView isn’t initializing correctly?

    Paresh Mayani's user avatar

    Paresh Mayani

    127k71 gold badges240 silver badges295 bronze badges

    asked Feb 19, 2011 at 6:17

    Gunslinger's user avatar

    2

    You’re getting NullPointerException because in your main.xml file you have defined a TextView not a WebView.

    Just change the TextView to WebView

          <?xml version="1.0" encoding="utf-8"?> 
            <LinearLayout xmlns:android="schemas.android.com/apk/res/android"; android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >
    
             <WebView android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:id="@+id/webView" />
     </LinearLayout>
    

    bob the dismantler's user avatar

    answered Feb 19, 2011 at 6:38

    Sankar Ganesh PMP's user avatar

    Sankar Ganesh PMPSankar Ganesh PMP

    11.9k11 gold badges56 silver badges90 bronze badges

    7

    Понравилась статья? Поделить с друзьями:
  • Error could not initialize directx 9 renderer painkiller что делать
  • Error could not handle the request как исправить
  • Error could not get the current mvc module paths
  • Error could not get primary adapter handle
  • Error could not get file size of file как исправить