How to get user theme dark or light in telegram web app using typescript vue 3?
- User
How to get user theme dark or light in telegram web app using typescript vue 3?
- Assistant
How to get user theme dark or light in telegram web app using typescript vue 3?
In a Telegram Web App, you can determine whether the user has selected a dark or light theme using Telegram's JavaScript API. Telegram Web Apps provide an interface to manage themes using the themeParams object, which you can access from the Web App object. Let's walk through how to implement this in a Vue 3 application with TypeScript.
Here’s how you can detect and react to the user’s theme preference:
Initialize the Telegram Web App: Make sure the Telegram Web App is properly initialized when your app starts.
Access the themeParams Object:
The themeParams object contains properties about the current theme, such as whether the theme is dark or light.
Handle Theme Changes:
Listen for theme change events by subscribing to the WebApp.onEvent method.
<template>
<div :class="appTheme">
<p>The current theme is: {{ theme }}</p>
</div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, watch } from "vue";
export default defineComponent({
name: "TelegramTheme",
setup() {
const theme = ref("light"); // default theme
const appTheme = ref(""); // CSS class to apply
onMounted(() => {
// Make sure the Telegram API is available
if (window.Telegram.WebApp) {
const tg = window.Telegram.WebApp;
// Update theme based on the current themeParams
const updateTheme = () => {
const isDarkTheme = tg.themeParams?.theme === "dark";
theme.value = isDarkTheme ? "dark" : "light";
appTheme.value = isDarkTheme ? "dark-theme" : "light-theme";
};
// Initialize the theme
updateTheme();
// Listen for theme change events
tg.onEvent("themeChanged", updateTheme);
}
});
return {
theme,
appTheme,
};
},
});
</script>
<style>
.dark-theme {
background-color: #1a1a1a;
color: white;
}
.light-theme {
background-color: white;
color: black;
}
</style>
Accessing Telegram Web App Object:
window.Telegram.WebApp object provides information about the Telegram Web App's runtime.themeParams in window.Telegram.WebApp to read details about the current theme.Checking Theme:
themeParams?.theme to determine if the theme is "dark" or "light".Listening for Theme Changes:
themeChanged event using onEvent("themeChanged"), you can dynamically react to user-initiated theme changes.Binding Theme to Vue Variables:
ref to create reactive values for the theme and apply them dynamically to the DOM.Styling Based on Themes:
dark-theme and light-theme) to adjust the UI appearance according to the theme.window.Telegram.onEvent("themeChanged") listener if your app adjusts other UI elements dynamically.This approach ensures a seamless experience for the user with consistent theme behavior in your Telegram Web App.
Not yet included in a published release.