TelegramMessenger / TGMiniAppsJsSDK

JavaScript SDK for Telegram Mini Apps
MIT License
18 stars 2 forks source link

`Telegram.WebApp.switchInlineQuery` not working inside a javascript module #4

Open hethon opened 4 months ago

hethon commented 4 months ago

I have a share button in my miniapp that when clicked switches to inline query interface using Telegram.WebApp.switchInlineQuery. It was all good and working fine until I decided to modularize my code with ES6Modules. It suddenly stopped working and there was no error messages or anything that would help me know the issue. Every other functionalities from Telegram.WebApp were working, it was only switchInlineQuery which wasn't working.

With some tiresome trials I narrowed down the error to a level that is easy to comprehend. The conclusion I came up with is that switchInlineQuery doesn't work if it's inside a module. In other words if you have a script called index.js and you have used switchInlineQuery inside it and you included it in your index.html as of type=module it won't work. But if you include it as a normal script it works.

You can find a minimum working example that can reproduce this issue 👇

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
  <title>Document</title>
  <style>
    body {
      margin: 0;
    }
    .container {
      display: flex;
      height: 100vh;
      color: #000;
      background-color: #fff;
    }
    .container > div {
      margin: auto;
    }
  </style>
</head>

<body>
  <div class="container">
    <div>Some Content Here</div>
  </div>

  <script type="module" src="./js/index.js"></script>
</body>

</html>

index.js

Telegram.WebApp.setHeaderColor("#fff");

Telegram.WebApp.MainButton.setParams({
  text: "Share",
  color: "#ff0000",
  is_visible: true,
});

Telegram.WebApp.MainButton.onClick(function () {
  Telegram.WebApp.switchInlineQuery(
    (query = "resource_id"),
    (choose_chat_types = ["users", "groups", "channels"])
  );
});
hethon commented 4 months ago

Instead of calling Telegram.WebApp.switchInlineQuery, directly calling Telegram.WebView.postEvent with eventType 'web_app_switch_inline_query' seems to have solved the issue. I still don't know why the issue appeared in the first place tho.