0
# Application Lifecycle
1
2
Application initialization, configuration, and lifecycle management including launch parameter handling, app closure, and configuration management for VK Mini Apps.
3
4
## Capabilities
5
6
### Application Initialization
7
8
Initialize the VK Bridge connection and establish communication with the VK client.
9
10
```typescript { .api }
11
/**
12
* Initialize VK Bridge connection
13
* Required as first method call to establish bridge communication
14
* @returns Confirmation of successful initialization
15
*/
16
function send(method: 'VKWebAppInit'): Promise<{ result: true }>;
17
```
18
19
**Usage Examples:**
20
21
```typescript
22
// Always initialize bridge first
23
try {
24
await bridge.send('VKWebAppInit');
25
console.log('VK Bridge initialized successfully');
26
27
// Now safe to use other bridge methods
28
const userInfo = await bridge.send('VKWebAppGetUserInfo');
29
const launchParams = await bridge.send('VKWebAppGetLaunchParams');
30
} catch (error) {
31
console.error('Failed to initialize VK Bridge:', error);
32
// Handle initialization failure
33
}
34
35
// With proper error handling
36
async function initializeApp() {
37
try {
38
const initResult = await bridge.send('VKWebAppInit');
39
if (initResult.result) {
40
console.log('Bridge ready for communication');
41
return true;
42
}
43
} catch (error) {
44
console.error('Initialization error:', error);
45
return false;
46
}
47
return false;
48
}
49
50
// Wait for initialization before app logic
51
const isReady = await initializeApp();
52
if (isReady) {
53
// Continue with app initialization
54
startApplication();
55
} else {
56
// Show error message to user
57
showInitializationError();
58
}
59
```
60
61
### Launch Parameters
62
63
Get launch parameters passed to the Mini App including user context, platform information, and app-specific data.
64
65
```typescript { .api }
66
/**
67
* Get launch parameters provided when Mini App was opened
68
* Contains user context, platform info, and launch-specific data
69
* @returns Complete launch parameters object
70
*/
71
function send(method: 'VKWebAppGetLaunchParams'): Promise<GetLaunchParamsResponse>;
72
73
interface GetLaunchParamsResponse {
74
/** User ID who launched the app */
75
vk_user_id: number;
76
/** VK application ID */
77
vk_app_id: number;
78
/** Platform where app is running */
79
vk_platform: EGetLaunchParamsResponsePlatforms;
80
/** User's language preference */
81
vk_language: EGetLaunchParamsResponseLanguages;
82
/** Whether user has installed the app (0 or 1) */
83
vk_is_app_user: 0 | 1;
84
/** Whether notifications are enabled (0 or 1) */
85
vk_are_notifications_enabled: 0 | 1;
86
/** Whether user added app to favorites (0 or 1) */
87
vk_is_favorite?: 0 | 1;
88
/** Launch timestamp */
89
vk_ts: number;
90
/** Cryptographic signature for parameter verification */
91
sign: string;
92
/** Community ID if launched from community context */
93
vk_group_id?: number;
94
/** User's role in community if applicable */
95
vk_viewer_group_role?: EGetLaunchParamsResponseGroupRole;
96
/** Referrer information */
97
vk_ref?: string;
98
/** Access token settings */
99
vk_access_token_settings?: string;
100
}
101
102
enum EGetLaunchParamsResponsePlatforms {
103
MOBILE_ANDROID = 'mobile_android',
104
MOBILE_ANDROID_MESSENGER = 'mobile_android_messenger',
105
MOBILE_IPHONE = 'mobile_iphone',
106
MOBILE_IPHONE_MESSENGER = 'mobile_iphone_messenger',
107
MOBILE_WEB = 'mobile_web',
108
DESKTOP_WEB = 'desktop_web'
109
}
110
111
enum EGetLaunchParamsResponseLanguages {
112
RU = 'ru',
113
UK = 'uk',
114
EN = 'en',
115
ES = 'es',
116
FI = 'fi',
117
DE = 'de',
118
IT = 'it'
119
}
120
121
enum EGetLaunchParamsResponseGroupRole {
122
NONE = 'none',
123
MEMBER = 'member',
124
MODER = 'moder',
125
EDITOR = 'editor',
126
ADMIN = 'admin'
127
}
128
```
129
130
**Usage Examples:**
131
132
```typescript
133
// Get launch parameters
134
const launchParams = await bridge.send('VKWebAppGetLaunchParams');
135
136
console.log('Launched by user:', launchParams.vk_user_id);
137
console.log('Platform:', launchParams.vk_platform);
138
console.log('Language:', launchParams.vk_language);
139
console.log('App user:', launchParams.vk_is_app_user ? 'Yes' : 'No');
140
141
// Platform-specific logic
142
switch (launchParams.vk_platform) {
143
case EGetLaunchParamsResponsePlatforms.MOBILE_ANDROID:
144
case EGetLaunchParamsResponsePlatforms.MOBILE_IPHONE:
145
console.log('Running on mobile app');
146
// Enable mobile-specific features
147
break;
148
case EGetLaunchParamsResponsePlatforms.DESKTOP_WEB:
149
console.log('Running on desktop web');
150
// Adjust UI for desktop
151
break;
152
case EGetLaunchParamsResponsePlatforms.MOBILE_WEB:
153
console.log('Running on mobile web');
154
// Mobile web optimizations
155
break;
156
}
157
158
// Localization based on language
159
const translations = {
160
[EGetLaunchParamsResponseLanguages.RU]: 'Добро пожаловать!',
161
[EGetLaunchParamsResponseLanguages.EN]: 'Welcome!',
162
[EGetLaunchParamsResponseLanguages.DE]: 'Willkommen!',
163
[EGetLaunchParamsResponseLanguages.ES]: '¡Bienvenido!'
164
};
165
166
const welcomeMessage = translations[launchParams.vk_language] || translations.en;
167
console.log(welcomeMessage);
168
169
// Community context handling
170
if (launchParams.vk_group_id) {
171
console.log('Launched from community:', launchParams.vk_group_id);
172
console.log('User role:', launchParams.vk_viewer_group_role);
173
174
// Show community-specific interface
175
if (launchParams.vk_viewer_group_role === EGetLaunchParamsResponseGroupRole.ADMIN) {
176
// Show admin features
177
showAdminPanel();
178
}
179
}
180
181
// Verify launch parameters (server-side)
182
async function verifyLaunchParams(params: GetLaunchParamsResponse): Promise<boolean> {
183
const response = await fetch('/api/verify-launch-params', {
184
method: 'POST',
185
headers: { 'Content-Type': 'application/json' },
186
body: JSON.stringify(params)
187
});
188
return response.ok;
189
}
190
```
191
192
### Application Configuration
193
194
Get current application configuration and environment settings from VK client.
195
196
```typescript { .api }
197
/**
198
* Get current application configuration
199
* Contains platform-specific settings and environment info
200
* @returns Configuration object with platform-specific data
201
*/
202
function send(method: 'VKWebAppGetConfig'): Promise<ParentConfigData>;
203
204
interface ParentConfigData {
205
/** Client version information */
206
version?: string;
207
/** Appearance scheme (light/dark theme) */
208
appearance?: AppearanceSchemeType;
209
/** Whether app can resize window */
210
can_resize?: boolean;
211
/** Current viewport dimensions */
212
viewport_width?: number;
213
viewport_height?: number;
214
/** Safe area insets for UI layout */
215
safe_area_insets?: {
216
top: number;
217
right: number;
218
bottom: number;
219
left: number;
220
};
221
}
222
223
enum AppearanceSchemeType {
224
VKCOM_LIGHT = 'vkcom_light',
225
VKCOM_DARK = 'vkcom_dark',
226
SPACE_GRAY = 'space_gray',
227
BRIGHT_LIGHT = 'bright_light'
228
}
229
```
230
231
**Usage Examples:**
232
233
```typescript
234
// Get app configuration
235
const config = await bridge.send('VKWebAppGetConfig');
236
237
console.log('Client version:', config.version);
238
console.log('Appearance:', config.appearance);
239
console.log('Viewport:', config.viewport_width, 'x', config.viewport_height);
240
241
// Adapt UI to appearance
242
if (config.appearance?.includes('dark')) {
243
document.body.classList.add('dark-theme');
244
} else {
245
document.body.classList.add('light-theme');
246
}
247
248
// Handle safe area insets (for mobile)
249
if (config.safe_area_insets) {
250
const { top, right, bottom, left } = config.safe_area_insets;
251
document.documentElement.style.setProperty('--safe-area-top', `${top}px`);
252
document.documentElement.style.setProperty('--safe-area-right', `${right}px`);
253
document.documentElement.style.setProperty('--safe-area-bottom', `${bottom}px`);
254
document.documentElement.style.setProperty('--safe-area-left', `${left}px`);
255
}
256
257
// Responsive design based on viewport
258
function adjustLayout(config: ParentConfigData) {
259
const isCompact = (config.viewport_width || 0) < 768;
260
261
if (isCompact) {
262
document.body.classList.add('compact-layout');
263
} else {
264
document.body.classList.add('wide-layout');
265
}
266
}
267
268
adjustLayout(config);
269
```
270
271
### Client Version Information
272
273
Get detailed information about the VK client version and capabilities.
274
275
```typescript { .api }
276
/**
277
* Get VK client version information
278
* @returns Client platform and version details
279
*/
280
function send(method: 'VKWebAppGetClientVersion'): Promise<{
281
platform: string;
282
version: string;
283
}>;
284
```
285
286
**Usage Examples:**
287
288
```typescript
289
// Get client version
290
const clientInfo = await bridge.send('VKWebAppGetClientVersion');
291
292
console.log('Client platform:', clientInfo.platform);
293
console.log('Client version:', clientInfo.version);
294
295
// Feature detection based on version
296
function parseVersion(version: string): number[] {
297
return version.split('.').map(Number);
298
}
299
300
const [major, minor, patch] = parseVersion(clientInfo.version);
301
302
// Enable features based on version
303
if (major >= 6 && minor >= 5) {
304
// Enable features available in 6.5+
305
enableAdvancedFeatures();
306
}
307
308
// Platform-specific version handling
309
switch (clientInfo.platform) {
310
case 'android':
311
if (major >= 6) {
312
enableAndroidSpecificFeatures();
313
}
314
break;
315
case 'ios':
316
if (major >= 6) {
317
enableIOSSpecificFeatures();
318
}
319
break;
320
case 'web':
321
enableWebFeatures();
322
break;
323
}
324
```
325
326
### Application Closure
327
328
Close the Mini App with optional status and payload data.
329
330
```typescript { .api }
331
/**
332
* Close the Mini App
333
* @param props.status - Closure status indicating success/failure
334
* @param props.payload - Optional data to pass back
335
* @returns Confirmation with returned payload
336
*/
337
function send(method: 'VKWebAppClose', props: {
338
status: AppCloseStatus;
339
payload?: any;
340
}): Promise<{ payload: any }>;
341
342
enum AppCloseStatus {
343
SUCCESS = 'success',
344
FAILED = 'failed'
345
}
346
```
347
348
**Usage Examples:**
349
350
```typescript
351
// Close app successfully
352
await bridge.send('VKWebAppClose', {
353
status: AppCloseStatus.SUCCESS,
354
payload: {
355
action: 'completed',
356
result: 'User finished task successfully',
357
data: { score: 100, level: 5 }
358
}
359
});
360
361
// Close app with failure
362
await bridge.send('VKWebAppClose', {
363
status: AppCloseStatus.FAILED,
364
payload: {
365
error: 'Network connection failed',
366
retry: true
367
}
368
});
369
370
// Graceful shutdown function
371
async function closeApp(success: boolean, data?: any) {
372
try {
373
// Save any pending data
374
await savePendingData();
375
376
// Close with appropriate status
377
await bridge.send('VKWebAppClose', {
378
status: success ? AppCloseStatus.SUCCESS : AppCloseStatus.FAILED,
379
payload: data
380
});
381
} catch (error) {
382
console.error('Error during app closure:', error);
383
// Force close without payload
384
await bridge.send('VKWebAppClose', {
385
status: AppCloseStatus.FAILED
386
});
387
}
388
}
389
390
// Handle user exit
391
document.getElementById('exit-button')?.addEventListener('click', () => {
392
closeApp(true, { reason: 'user_exit' });
393
});
394
395
// Handle errors
396
window.addEventListener('error', (event) => {
397
closeApp(false, {
398
error: event.error?.message || 'Unknown error',
399
stack: event.error?.stack
400
});
401
});
402
```
403
404
## Complete Initialization Flow
405
406
```typescript
407
async function initializeVKMiniApp() {
408
try {
409
// 1. Initialize bridge
410
console.log('Initializing VK Bridge...');
411
await bridge.send('VKWebAppInit');
412
413
// 2. Get launch parameters
414
console.log('Getting launch parameters...');
415
const launchParams = await bridge.send('VKWebAppGetLaunchParams');
416
417
// 3. Get app configuration
418
console.log('Getting app configuration...');
419
const config = await bridge.send('VKWebAppGetConfig');
420
421
// 4. Get client version
422
console.log('Getting client version...');
423
const clientInfo = await bridge.send('VKWebAppGetClientVersion');
424
425
// 5. Apply configuration
426
applyTheme(config.appearance);
427
adjustLayout(config);
428
handleSafeArea(config.safe_area_insets);
429
430
// 6. Set up localization
431
setLanguage(launchParams.vk_language);
432
433
// 7. Log initialization success
434
console.log('VK Mini App initialized successfully', {
435
userId: launchParams.vk_user_id,
436
platform: launchParams.vk_platform,
437
clientVersion: clientInfo.version,
438
appearance: config.appearance
439
});
440
441
return {
442
launchParams,
443
config,
444
clientInfo
445
};
446
447
} catch (error) {
448
console.error('Failed to initialize VK Mini App:', error);
449
450
// Show error to user
451
showError('Failed to initialize app. Please try again.');
452
453
// Close app with failure status
454
await bridge.send('VKWebAppClose', {
455
status: AppCloseStatus.FAILED,
456
payload: { error: 'initialization_failed' }
457
});
458
459
throw error;
460
}
461
}
462
463
// Start the app
464
initializeVKMiniApp().then((appContext) => {
465
// App successfully initialized, start main application logic
466
startMainApplication(appContext);
467
});
468
```