Bridge library for VK Mini Apps to communicate with VK clients across iOS, Android, and Web platforms
—
Application initialization, configuration, and lifecycle management including launch parameter handling, app closure, and configuration management for VK Mini Apps.
Initialize the VK Bridge connection and establish communication with the VK client.
/**
* Initialize VK Bridge connection
* Required as first method call to establish bridge communication
* @returns Confirmation of successful initialization
*/
function send(method: 'VKWebAppInit'): Promise<{ result: true }>;Usage Examples:
// Always initialize bridge first
try {
await bridge.send('VKWebAppInit');
console.log('VK Bridge initialized successfully');
// Now safe to use other bridge methods
const userInfo = await bridge.send('VKWebAppGetUserInfo');
const launchParams = await bridge.send('VKWebAppGetLaunchParams');
} catch (error) {
console.error('Failed to initialize VK Bridge:', error);
// Handle initialization failure
}
// With proper error handling
async function initializeApp() {
try {
const initResult = await bridge.send('VKWebAppInit');
if (initResult.result) {
console.log('Bridge ready for communication');
return true;
}
} catch (error) {
console.error('Initialization error:', error);
return false;
}
return false;
}
// Wait for initialization before app logic
const isReady = await initializeApp();
if (isReady) {
// Continue with app initialization
startApplication();
} else {
// Show error message to user
showInitializationError();
}Get launch parameters passed to the Mini App including user context, platform information, and app-specific data.
/**
* Get launch parameters provided when Mini App was opened
* Contains user context, platform info, and launch-specific data
* @returns Complete launch parameters object
*/
function send(method: 'VKWebAppGetLaunchParams'): Promise<GetLaunchParamsResponse>;
interface GetLaunchParamsResponse {
/** User ID who launched the app */
vk_user_id: number;
/** VK application ID */
vk_app_id: number;
/** Platform where app is running */
vk_platform: EGetLaunchParamsResponsePlatforms;
/** User's language preference */
vk_language: EGetLaunchParamsResponseLanguages;
/** Whether user has installed the app (0 or 1) */
vk_is_app_user: 0 | 1;
/** Whether notifications are enabled (0 or 1) */
vk_are_notifications_enabled: 0 | 1;
/** Whether user added app to favorites (0 or 1) */
vk_is_favorite?: 0 | 1;
/** Launch timestamp */
vk_ts: number;
/** Cryptographic signature for parameter verification */
sign: string;
/** Community ID if launched from community context */
vk_group_id?: number;
/** User's role in community if applicable */
vk_viewer_group_role?: EGetLaunchParamsResponseGroupRole;
/** Referrer information */
vk_ref?: string;
/** Access token settings */
vk_access_token_settings?: string;
}
enum EGetLaunchParamsResponsePlatforms {
MOBILE_ANDROID = 'mobile_android',
MOBILE_ANDROID_MESSENGER = 'mobile_android_messenger',
MOBILE_IPHONE = 'mobile_iphone',
MOBILE_IPHONE_MESSENGER = 'mobile_iphone_messenger',
MOBILE_WEB = 'mobile_web',
DESKTOP_WEB = 'desktop_web'
}
enum EGetLaunchParamsResponseLanguages {
RU = 'ru',
UK = 'uk',
EN = 'en',
ES = 'es',
FI = 'fi',
DE = 'de',
IT = 'it'
}
enum EGetLaunchParamsResponseGroupRole {
NONE = 'none',
MEMBER = 'member',
MODER = 'moder',
EDITOR = 'editor',
ADMIN = 'admin'
}Usage Examples:
// Get launch parameters
const launchParams = await bridge.send('VKWebAppGetLaunchParams');
console.log('Launched by user:', launchParams.vk_user_id);
console.log('Platform:', launchParams.vk_platform);
console.log('Language:', launchParams.vk_language);
console.log('App user:', launchParams.vk_is_app_user ? 'Yes' : 'No');
// Platform-specific logic
switch (launchParams.vk_platform) {
case EGetLaunchParamsResponsePlatforms.MOBILE_ANDROID:
case EGetLaunchParamsResponsePlatforms.MOBILE_IPHONE:
console.log('Running on mobile app');
// Enable mobile-specific features
break;
case EGetLaunchParamsResponsePlatforms.DESKTOP_WEB:
console.log('Running on desktop web');
// Adjust UI for desktop
break;
case EGetLaunchParamsResponsePlatforms.MOBILE_WEB:
console.log('Running on mobile web');
// Mobile web optimizations
break;
}
// Localization based on language
const translations = {
[EGetLaunchParamsResponseLanguages.RU]: 'Добро пожаловать!',
[EGetLaunchParamsResponseLanguages.EN]: 'Welcome!',
[EGetLaunchParamsResponseLanguages.DE]: 'Willkommen!',
[EGetLaunchParamsResponseLanguages.ES]: '¡Bienvenido!'
};
const welcomeMessage = translations[launchParams.vk_language] || translations.en;
console.log(welcomeMessage);
// Community context handling
if (launchParams.vk_group_id) {
console.log('Launched from community:', launchParams.vk_group_id);
console.log('User role:', launchParams.vk_viewer_group_role);
// Show community-specific interface
if (launchParams.vk_viewer_group_role === EGetLaunchParamsResponseGroupRole.ADMIN) {
// Show admin features
showAdminPanel();
}
}
// Verify launch parameters (server-side)
async function verifyLaunchParams(params: GetLaunchParamsResponse): Promise<boolean> {
const response = await fetch('/api/verify-launch-params', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(params)
});
return response.ok;
}Get current application configuration and environment settings from VK client.
/**
* Get current application configuration
* Contains platform-specific settings and environment info
* @returns Configuration object with platform-specific data
*/
function send(method: 'VKWebAppGetConfig'): Promise<ParentConfigData>;
interface ParentConfigData {
/** Client version information */
version?: string;
/** Appearance scheme (light/dark theme) */
appearance?: AppearanceSchemeType;
/** Whether app can resize window */
can_resize?: boolean;
/** Current viewport dimensions */
viewport_width?: number;
viewport_height?: number;
/** Safe area insets for UI layout */
safe_area_insets?: {
top: number;
right: number;
bottom: number;
left: number;
};
}
enum AppearanceSchemeType {
VKCOM_LIGHT = 'vkcom_light',
VKCOM_DARK = 'vkcom_dark',
SPACE_GRAY = 'space_gray',
BRIGHT_LIGHT = 'bright_light'
}Usage Examples:
// Get app configuration
const config = await bridge.send('VKWebAppGetConfig');
console.log('Client version:', config.version);
console.log('Appearance:', config.appearance);
console.log('Viewport:', config.viewport_width, 'x', config.viewport_height);
// Adapt UI to appearance
if (config.appearance?.includes('dark')) {
document.body.classList.add('dark-theme');
} else {
document.body.classList.add('light-theme');
}
// Handle safe area insets (for mobile)
if (config.safe_area_insets) {
const { top, right, bottom, left } = config.safe_area_insets;
document.documentElement.style.setProperty('--safe-area-top', `${top}px`);
document.documentElement.style.setProperty('--safe-area-right', `${right}px`);
document.documentElement.style.setProperty('--safe-area-bottom', `${bottom}px`);
document.documentElement.style.setProperty('--safe-area-left', `${left}px`);
}
// Responsive design based on viewport
function adjustLayout(config: ParentConfigData) {
const isCompact = (config.viewport_width || 0) < 768;
if (isCompact) {
document.body.classList.add('compact-layout');
} else {
document.body.classList.add('wide-layout');
}
}
adjustLayout(config);Get detailed information about the VK client version and capabilities.
/**
* Get VK client version information
* @returns Client platform and version details
*/
function send(method: 'VKWebAppGetClientVersion'): Promise<{
platform: string;
version: string;
}>;Usage Examples:
// Get client version
const clientInfo = await bridge.send('VKWebAppGetClientVersion');
console.log('Client platform:', clientInfo.platform);
console.log('Client version:', clientInfo.version);
// Feature detection based on version
function parseVersion(version: string): number[] {
return version.split('.').map(Number);
}
const [major, minor, patch] = parseVersion(clientInfo.version);
// Enable features based on version
if (major >= 6 && minor >= 5) {
// Enable features available in 6.5+
enableAdvancedFeatures();
}
// Platform-specific version handling
switch (clientInfo.platform) {
case 'android':
if (major >= 6) {
enableAndroidSpecificFeatures();
}
break;
case 'ios':
if (major >= 6) {
enableIOSSpecificFeatures();
}
break;
case 'web':
enableWebFeatures();
break;
}Close the Mini App with optional status and payload data.
/**
* Close the Mini App
* @param props.status - Closure status indicating success/failure
* @param props.payload - Optional data to pass back
* @returns Confirmation with returned payload
*/
function send(method: 'VKWebAppClose', props: {
status: AppCloseStatus;
payload?: any;
}): Promise<{ payload: any }>;
enum AppCloseStatus {
SUCCESS = 'success',
FAILED = 'failed'
}Usage Examples:
// Close app successfully
await bridge.send('VKWebAppClose', {
status: AppCloseStatus.SUCCESS,
payload: {
action: 'completed',
result: 'User finished task successfully',
data: { score: 100, level: 5 }
}
});
// Close app with failure
await bridge.send('VKWebAppClose', {
status: AppCloseStatus.FAILED,
payload: {
error: 'Network connection failed',
retry: true
}
});
// Graceful shutdown function
async function closeApp(success: boolean, data?: any) {
try {
// Save any pending data
await savePendingData();
// Close with appropriate status
await bridge.send('VKWebAppClose', {
status: success ? AppCloseStatus.SUCCESS : AppCloseStatus.FAILED,
payload: data
});
} catch (error) {
console.error('Error during app closure:', error);
// Force close without payload
await bridge.send('VKWebAppClose', {
status: AppCloseStatus.FAILED
});
}
}
// Handle user exit
document.getElementById('exit-button')?.addEventListener('click', () => {
closeApp(true, { reason: 'user_exit' });
});
// Handle errors
window.addEventListener('error', (event) => {
closeApp(false, {
error: event.error?.message || 'Unknown error',
stack: event.error?.stack
});
});async function initializeVKMiniApp() {
try {
// 1. Initialize bridge
console.log('Initializing VK Bridge...');
await bridge.send('VKWebAppInit');
// 2. Get launch parameters
console.log('Getting launch parameters...');
const launchParams = await bridge.send('VKWebAppGetLaunchParams');
// 3. Get app configuration
console.log('Getting app configuration...');
const config = await bridge.send('VKWebAppGetConfig');
// 4. Get client version
console.log('Getting client version...');
const clientInfo = await bridge.send('VKWebAppGetClientVersion');
// 5. Apply configuration
applyTheme(config.appearance);
adjustLayout(config);
handleSafeArea(config.safe_area_insets);
// 6. Set up localization
setLanguage(launchParams.vk_language);
// 7. Log initialization success
console.log('VK Mini App initialized successfully', {
userId: launchParams.vk_user_id,
platform: launchParams.vk_platform,
clientVersion: clientInfo.version,
appearance: config.appearance
});
return {
launchParams,
config,
clientInfo
};
} catch (error) {
console.error('Failed to initialize VK Mini App:', error);
// Show error to user
showError('Failed to initialize app. Please try again.');
// Close app with failure status
await bridge.send('VKWebAppClose', {
status: AppCloseStatus.FAILED,
payload: { error: 'initialization_failed' }
});
throw error;
}
}
// Start the app
initializeVKMiniApp().then((appContext) => {
// App successfully initialized, start main application logic
startMainApplication(appContext);
});Install with Tessl CLI
npx tessl i tessl/npm-vkontakte--vk-bridge