telegram bot webapp initData() is empty on Google app script and MainButton.onClick is not working

2.4k Views Asked by At

telegram bot webapp initData() is empty on Google app script and MainButton.onClick is not working. please help. `

<!DOCTYPE html>
    
<html>
  
  <head>
    <script src="https://telegram.org/js/telegram-web-app.js"></script>
    <base target="_self">
    
  </head>
  <body>

    <div class="container">
      <h1>My Title</h1>
      <div class="row" id="tg"></div>
      
      
      <div class="row"  >
        <button id="btn">all_inclusive</button>
      </div>
    </div>
    <script>
      
            window.Telegram.WebApp.ready();
            window.Telegram.WebApp.expand();
            // initData is empty object
            let initData = window.Telegram.WebApp.initData;
             // initDataUnsafe is empty object,too
            let initDataUnsafe = window.Telegram.WebApp.initDataUnsafe;
            window.Telegram.WebApp.MainButton.showProgress()
            window.Telegram.WebApp.MainButton.setText('submit').show().enable()
            window.Telegram.WebApp.MainButton.isProgressVisible = "true"
            //This Event is not working, Why?
            window.Telegram.WebApp.MainButton.onClick(() => {alert('submitted')});
            window.document.getElementById('tg').innerHTML =             JSON.stringify(window.Telegram.WebA
           

</script>
  </body>
</html>

`

I want to build a webapp on telegram, but i can get the user's id

2

There are 2 best solutions below

0
On

initData will be empty if the WebApp is opened from a custom keyboard

use inline_keyboard

https://core.telegram.org/bots/webapps#webappinitdata

0
On

I understand that the question may already be irrelevant, but I will leave my answer here just in case. InitData may be empty when you open the application from a custom keyboard, so it is better to use the built-in keyboard. also initData may be missing when the user in the application, at the top, presses the update button. After that, the initData is also empty, regardless of how the application was opened. I hope I helped you. Also, if you are looking for how to check the validity of the user, i.e. check the window.Telegram.WebApp.initData field, I can recommend the TgWebValid package, it will cope with this perfectly and very easily. I will leave you the link