forked from revenkroz/telegram-web-app-bot-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
837 lines (786 loc) · 31.5 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="MobileOptimized" content="176" />
<meta name="HandheldFriendly" content="True" />
<meta name="robots" content="noindex,nofollow" />
<title></title>
<script src="https://telegram.org/js/telegram-web-app.js?1"></script>
<script>
function setThemeClass() {
document.documentElement.className = Telegram.WebApp.colorScheme;
}
Telegram.WebApp.onEvent('themeChanged', setThemeClass);
setThemeClass();
</script>
<style>
body {
--bg-color: var(--tg-theme-bg-color, #fff);
font-family: sans-serif;
background-color: var(--bg-color);
color: var(--tg-theme-text-color, #222);
font-size: 14px;
margin: 0;
padding: 0;
color-scheme: var(--tg-color-scheme);
}
body.gray {
background-color: var(--tg-theme-secondary-bg-color, #efefef);
}
a {
color: var(--tg-theme-link-color, #2678b6);
}
.btn {
font-size: 14px;
padding: 10px 17px;
}
.btn-primary {
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #fff);
border: none;
}
button {
display: block;
width: 100%;
font-size: 14px;
margin: 15px 0;
padding: 12px 20px;
border: none;
border-radius: 4px;
background-color: var(--tg-theme-button-color, #50a8eb);
color: var(--tg-theme-button-text-color, #ffffff);
cursor: pointer;
}
.main-container {
padding: 15px;
}
.list-header {
text-transform: uppercase;
font-size: .92em;
color: var(--tg-theme-hint-color, #ccc);
margin: 0 0 10px;
}
a.list-group-item,
button.list-group-item {
color: var(--tg-theme-text-color, #222);
}
.main-container p {
margin: 0 0 10px;
}
.main-container pre,
.main-container > .btn {
margin: 0 0 7px;
}
.main-container pre + .hint,
.main-container > .btn + .hint {
text-align: center;
margin: 0 0 15px;
}
button[disabled] {
opacity: 0.6;
cursor: auto;
pointer-events: none;
}
button.close_btn {
/*position: fixed;*/
position: absolute;
left: 0;
right: 0;
bottom: 0;
border-radius: 0;
margin: 0;
padding: 16px 20px;
text-transform: uppercase;
}
input[type="text"],
.input[contenteditable] {
display: block;
box-sizing: border-box;
font-size: 14px;
width: 100%;
padding: 12px 20px;
margin: 15px 0;
border: 1px solid var(--tg-theme-link-color, #000);
background-color: var(--tg-theme-bg-color, #ffffff);
border-radius: 4px;
color: var(--tg-theme-text-color, #222222);
text-align: start;
}
input[type="text"]::-webkit-input-placeholder {
color: var(--tg-theme-hint-color, #ccc);
}
input[type="text"]::-moz-placeholder {
color: var(--tg-theme-hint-color, #ccc);
}
input[type="text"]:-ms-input-placeholder {
color: var(--tg-theme-hint-color, #ccc);
}
.input[data-placeholder] {
position: relative;
}
.input[data-placeholder]:empty:before {
position: absolute;
left: 0;
right: 0;
content: attr(data-placeholder);
color: var(--tg-theme-hint-color, #ccc);
padding: 0 20px;
font-weight: normal;
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
pointer-events: none;
z-index: -1;
}
section {
padding: 15px;
text-align: center;
background-color: var(--bg-color, #ffffff);
}
section#top_sect {
background-color: var(--tg-theme-bg-color, #ffffff);
}
section#top_sect.second {
background-color: var(--tg-theme-secondary-bg-color, #efefef);
}
section .sect_row {
margin: 10px 0;
}
section + section {
padding: 0 15px 65px;
}
p {
margin: 40px 0 15px;
}
ul {
text-align: left;
}
li {
color: var(--tg-theme-hint-color, #a8a8a8);
}
textarea {
width: 100%;
box-sizing: border-box;
padding: 7px;
}
pre {
background: rgba(0, 0, 0, .07);
color: var(--tg-theme-text-color, #222);
font-size: 12px;
border: none;
border-radius: 4px;
padding: 8px;
margin: 7px 0;
word-break: break-word;
white-space: pre-wrap;
text-align: left;
}
.dark pre {
background: rgba(255, 255, 255, .15);
}
.chat_img {
width: 30px;
border-radius: 15px;
margin-right: 10px;
}
.columns {
display: flex;
}
.columns>* {
flex-grow: 1;
}
.hint {
font-size: .8em;
color: var(--tg-theme-hint-color, #a8a8a8);
}
.ok {
color: green;
}
.err {
color: red;
}
.status_need {
display: none;
}
#fixed_wrap {
position: fixed;
left: 0;
right: 0;
top: 0;
transform: translateY(100vh);
}
.viewport-container {
position: fixed;
left: 0;
right: 0;
top: 0;
height: var(--tg-viewport-stable-height, 100vh);
transition: height .2s ease;
}
.viewport-container .main-container {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
}
.viewport-container .main-container button {
width: auto;
}
.viewport-border,
.viewport-stable_border {
position: fixed;
left: 0;
right: 0;
top: 0;
height: var(--tg-viewport-height, 100vh);
pointer-events: none;
}
.viewport-stable_border {
height: var(--tg-viewport-stable-height, 100vh);
}
.viewport-border:before,
.viewport-stable_border:before {
content: attr(text);
display: inline-block;
position: absolute;
background: gray;
right: 0;
top: 0;
font-size: 7px;
padding: 2px 4px;
vertical-align: top;
}
.viewport-stable_border:before {
background: green;
left: 0;
right: auto;
}
.viewport-border:after,
.viewport-stable_border:after {
content: '';
display: block;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
border: 2px dashed gray;
}
.viewport-stable_border:after {
border-color: green;
}
small {
font-size: 12px;
}
</style>
</head>
<body class="" style="visibility: visible;">
<section id="top_sect" class="second">
<h2>Signup</h2>
<form action="process_signup.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Sign Up">
</form>
</section>
<section>
<div id="btn_status" class="hint" style="display: none;">
</div>
<p>Test links:</p>
<ul>
<li><a id="regular_link" href="">Regular link #2</a> (opens inside webview)</li>
<li><a href="https://telegram.org/" target="_blank">target="_blank" link</a> (opens outside webview)</li>
<li><a href="javascript:window.open('https://telegram.org/');">window.open() link</a> (opens outside webview)</li>
<li><a href="https://t.me/like">LikeBot t.me link</a> (opens inside Telegram app)</li>
<li><a href="javascript:Telegram.WebApp.openTelegramLink('https://t.me/vote');">web_app_open_tg_link()</a> (opens inside Telegram app)</li>
<li><a href="javascript:Telegram.WebApp.openLink('https://google.com/');">web_app_open_link()</a> (opens outside webview)</li>
<li><a href="tg://resolve?domain=vote">VoteBot tg:// link</a> (does not open)</li>
<li><a href="javascript:Telegram.WebApp.openLink('https://telegra.ph/api',{try_instant_view:true});">web_app_open_link({try_instant_view:true})</a> (opens IV inside Telegram app)</li>
</ul>
<p>Test permissions:</p>
<ul>
<li><a href="javascript:;" onclick="return DemoApp.requestLocation(this);">Request Location</a> <span></span></li>
<li><a href="javascript:;" onclick="return DemoApp.requestVideo(this);">Request Video</a> <span></span></li>
<li><a href="javascript:;" onclick="return DemoApp.requestAudio(this);">Request Audio</a> <span></span></li>
<li><a href="javascript:;" onclick="return DemoApp.requestAudioVideo(this);">Request Audio+Video</a> <span></span></li>
<li><a href="javascript:;" onclick="return DemoApp.testClipboard(this);" id="clipboard_test">Read from clipboard</a> <span></span></li>
</ul>
<p>Test alerts:</p>
<div class="columns">
<ul>
<li><a href="javascript:;" onclick="alert('Hello!');">alert</a></li>
<li><a href="javascript:;" onclick="confirm('Are you sure?');">confirm</a></li>
<li><a href="javascript:;" onclick="prompt('How old are you?');">prompt</a></li>
</ul>
<ul>
<li><a href="javascript:;" onclick="DemoApp.showAlert('Hello!');">showAlert</a></li>
<li><a href="javascript:;" onclick="DemoApp.showConfirm('Are you sure?');">showConfirm</a></li>
<li><a href="javascript:;" onclick="DemoApp.showPopup();">showPopup</a></li>
<li><a href="javascript:;" onclick="DemoApp.showScanQrPopup();">showScanQrPopup</a></li>
<li><a href="javascript:;" onclick="DemoApp.showScanQrPopup(true);">showScanQrPopup (links only)</a></li>
</ul>
</div>
<p>Haptics:</p>
<ul>
<li>Impact: <a href="javascript:Telegram.WebApp.HapticFeedback.impactOccurred('heavy');">heavy</a>, <a href="javascript:Telegram.WebApp.HapticFeedback.impactOccurred('light');">light</a>, <a href="javascript:Telegram.WebApp.HapticFeedback.impactOccurred('medium');">medium</a>, <a href="javascript:Telegram.WebApp.HapticFeedback.impactOccurred('rigid');">rigid</a>, <a href="javascript:Telegram.WebApp.HapticFeedback.impactOccurred('soft');">soft</a><br><br></li>
<li>Notification: <a href="javascript:Telegram.WebApp.HapticFeedback.notificationOccurred('error');">error</a>, <a href="javascript:Telegram.WebApp.HapticFeedback.notificationOccurred('success');">success</a>, <a href="javascript:Telegram.WebApp.HapticFeedback.notificationOccurred('warning');">warning</a><br><br></li>
<li>Selection: <a href="javascript:Telegram.WebApp.HapticFeedback.selectionChanged();">changed</a><br><br></li>
</ul>
<pre><code id="webview_data"></code></pre>
<div class="hint">
Data passed to webview.
<span id="webview_data_status" class="status_need">Checking hash...</span>
</div>
<pre><code id="theme_data"></code></pre>
<div class="hint">
Theme params
</div>
<div class="hint">
Version: <span id="ver"></span>,
platform: <span id="platform"></span>
</div>
</section>
<div class="viewport-border"></div>
<div class="viewport-stable_border"></div>
<script type="application/javascript">
/*
* This is a demo code for Telegram WebApp for Bots
* It contains basic examples of how to use the API
* Note: all requests to backend are disabled in this demo, you should use your own backend
*/
const DemoApp = {
initData: Telegram.WebApp.initData || '',
initDataUnsafe: Telegram.WebApp.initDataUnsafe || {},
MainButton: Telegram.WebApp.MainButton,
init(options) {
document.body.style.visibility = '';
Telegram.WebApp.ready();
Telegram.WebApp.MainButton.setParams({
text: 'CLOSE WEBVIEW',
is_visible: true
}).onClick(DemoApp.close);
},
expand() {
Telegram.WebApp.expand();
},
close() {
Telegram.WebApp.close();
},
toggleMainButton(el) {
const mainButton = Telegram.WebApp.MainButton;
if (mainButton.isVisible) {
mainButton.hide();
el.innerHTML = 'Show Main Button';
} else {
mainButton.show();
el.innerHTML = 'Hide Main Button';
}
},
// actions
sendMessage(msg_id, with_webview) {
if (!DemoApp.initDataUnsafe.query_id) {
alert('WebViewQueryId not defined');
return;
}
document.querySelectorAll('button').forEach((btn) => btn.disabled = true);
const btn = document.querySelector('#btn_status');
btn.textContent = 'Sending...';
DemoApp.apiRequest('sendMessage', {
msg_id: msg_id || '',
with_webview: !DemoApp.initDataUnsafe.receiver && with_webview ? 1 : 0
}, function(result) {
document.querySelectorAll('button').forEach((btn) => btn.disabled = false);
if (result.response) {
if (result.response.ok) {
btn.textContent = 'Message sent successfully!';
btn.className = 'ok';
btn.style.display = 'block';
} else {
btn.textContent = result.response.description;
btn.className = 'err';
btn.style.display = 'block';
alert(result.response.description);
}
} else if (result.error) {
btn.textContent = result.error;
btn.className = 'err';
btn.style.display = 'block';
alert(result.error);
} else {
btn.textContent = 'Unknown error';
btn.className = 'err';
btn.style.display = 'block';
alert('Unknown error');
}
});
},
changeMenuButton(close) {
document.querySelectorAll('button').forEach((btn) => btn.disabled = true);
const btnStatus = document.querySelector('#btn_status');
btnStatus.textContent = 'Changing button...';
DemoApp.apiRequest('changeMenuButton', {}, function(result) {
document.querySelectorAll('button').forEach((btn) => btn.disabled = false);
if (result.response) {
if (result.response.ok) {
btnStatus.textContent = 'Button changed!';
btnStatus.className = 'ok';
btnStatus.style.display = 'block';
Telegram.WebApp.close();
} else {
btnStatus.textContent = result.response.description;
btnStatus.className = 'err';
btnStatus.style.display = 'block';
alert(result.response.description);
}
} else if (result.error) {
btnStatus.textContent = result.error;
btnStatus.className = 'err';
btnStatus.style.display = 'block';
alert(result.error);
} else {
btnStatus.textContent = 'Unknown error';
btnStatus.className = 'err';
btnStatus.style.display = 'block';
alert('Unknown error');
}
});
if (close) {
setTimeout(function() {
Telegram.WebApp.close();
}, 50);
}
},
checkInitData() {
const webViewStatus = document.querySelector('#webview_data_status');
if (DemoApp.initDataUnsafe.query_id &&
DemoApp.initData &&
webViewStatus.classList.contains('status_need')
) {
webViewStatus.classList.remove('status_need');
DemoApp.apiRequest('checkInitData', {}, function(result) {
if (result.ok) {
webViewStatus.textContent = 'Hash is correct (async)';
webViewStatus.className = 'ok';
} else {
webViewStatus.textContent = result.error + ' (async)';
webViewStatus.className = 'err';
}
});
}
},
sendText(spam) {
const textField = document.querySelector('#text_field');
const text = textField.value;
if (!text.length) {
return textField.focus();
}
if (byteLength(text) > 4096) {
return alert('Text is too long');
}
const repeat = spam ? 10 : 1;
for (let i = 0; i < repeat; i++) {
Telegram.WebApp.sendData(text);
}
},
sendTime(spam) {
const repeat = spam ? 10 : 1;
for (let i = 0; i < repeat; i++) {
Telegram.WebApp.sendData(new Date().toString());
}
},
// Alerts
showAlert(message) {
Telegram.WebApp.showAlert(message);
},
showConfirm(message) {
Telegram.WebApp.showConfirm(message);
},
showPopup() {
Telegram.WebApp.showPopup({
title: 'Popup title',
message: 'Popup message',
buttons: [
{id: 'delete', type: 'destructive', text: 'Delete all'},
{id: 'faq', type: 'default', text: 'Open FAQ'},
{type: 'cancel'},
]
}, function(buttonId) {
if (buttonId === 'delete') {
DemoApp.showAlert("'Delete all' selected");
} else if (buttonId === 'faq') {
Telegram.WebApp.openLink('https://telegram.org/faq');
}
});
},
showScanQrPopup: function(linksOnly) {
Telegram.WebApp.showScanQrPopup({
text: linksOnly ? 'with any link' : 'for test purposes'
}, function(text) {
if (linksOnly) {
const lowerText = text.toString().toLowerCase();
if (lowerText.substring(0, 7) === 'http://' ||
lowerText.substring(0, 8) === 'https://'
) {
setTimeout(function() {
Telegram.WebApp.openLink(text);
}, 50);
return true;
}
} else {
DemoApp.showAlert(text);
return true;
}
});
},
// Permissions
requestLocation(el) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
el.nextElementSibling.innerHTML = '(' + position.coords.latitude + ', ' + position.coords.longitude + ')';
el.nextElementSibling.className = 'ok';
});
} else {
el.nextElementSibling.innerHTML = 'Geolocation is not supported in this browser.';
el.nextElementSibling.className = 'err';
}
return false;
},
requestVideo(el) {
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({ audio: false, video: true }).then(function(stream) {
el.nextElementSibling.innerHTML = '(Access granted)';
});
} else {
el.nextElementSibling.innerHTML = 'Media devices is not supported in this browser.';
el.nextElementSibling.className = 'err';
}
return false;
},
requestAudio(el) {
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(function(stream) {
el.nextElementSibling.innerHTML = '(Access granted)';
el.nextElementSibling.className = 'ok';
});
} else {
el.nextElementSibling.innerHTML = 'Media devices is not supported in this browser.';
el.nextElementSibling.className = 'err';
}
return false;
},
requestAudioVideo(el) {
if (navigator.mediaDevices) {
navigator.mediaDevices.getUserMedia({ audio: true, video: true }).then(function(stream) {
el.nextElementSibling.innerHTML = '(Access granted)';
el.nextElementSibling.className = 'ok';
});
} else {
el.nextElementSibling.innerHTML = 'Media devices is not supported in this browser.';
el.nextElementSibling.className = 'err';
}
return false;
},
testClipboard(el) {
Telegram.WebApp.readTextFromClipboard(function(clipText) {
if (clipText === null) {
el.nextElementSibling.innerHTML = 'Clipboard text unavailable.';
el.nextElementSibling.className = 'err';
} else {
el.nextElementSibling.innerHTML = '(Read from clipboard: «' + clipText + '»)';
el.nextElementSibling.className = 'ok';
}
});
return false;
},
// Other
apiRequest(method, data, onCallback) {
// DISABLE BACKEND FOR FRONTEND DEMO
// YOU CAN USE YOUR OWN REQUESTS TO YOUR OWN BACKEND
// CHANGE THIS CODE TO YOUR OWN
return onCallback && onCallback({error: 'This function (' + method + ') should send requests to your backend. Please, change this code to your own.'});
const authData = DemoApp.initData || '';
fetch('/demo/api', {
method: 'POST',
body: JSON.stringify(Object.assign(data, {
_auth: authData,
method: method,
})),
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
return response.json();
}).then(function(result) {
onCallback && onCallback(result);
}).catch(function(error) {
onCallback && onCallback({error: 'Server error'});
});
}
}
const DemoAppMenu = {
init() {
DemoApp.init();
document.body.classList.add('gray');
Telegram.WebApp.setHeaderColor('secondary_bg_color');
}
};
const DemoAppInitData = {
init() {
DemoApp.init();
Telegram.WebApp.onEvent('themeChanged', function() {
document.getElementById('theme_data').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
});
document.getElementById('webview_data').innerHTML = JSON.stringify(DemoApp.initDataUnsafe, null, 2);
document.getElementById('theme_data').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
DemoApp.checkInitData();
}
};
const DemoAppViewport = {
init() {
DemoApp.init();
Telegram.WebApp.onEvent('viewportChanged', DemoAppViewport.setData);
DemoAppViewport.setData();
},
setData() {
document.querySelector('.viewport-border')
.setAttribute('text', window.innerWidth + ' x ' + round(Telegram.WebApp.viewportHeight, 2))
document.querySelector('.viewport-stable_border')
.setAttribute('text', window.innerWidth + ' x ' + round(Telegram.WebApp.viewportStableHeight, 2) +
' | is_expanded: ' + (Telegram.WebApp.isExpanded ? 'true' : 'false'));
}
};
function byteLength(str) {
if (window.Blob) {
try { return new Blob([str]).size; } catch (e) {}
}
let s = str.length;
for (let i = str.length - 1; i >= 0; i--) {
const code = str.charCodeAt(i);
if (code > 0x7f && code <= 0x7ff) {
s++;
} else if (code > 0x7ff && code <= 0xffff) {
s+=2;
}
if (code >= 0xDC00 && code <= 0xDFFF) {
i--;
}
}
return s;
}
function round(val, d) {
const k = Math.pow(10, d || 0);
return Math.round(val * k) / k;
}
</script>
<script type="application/javascript">
/*
* This part of code is used to initialize the demo app and set up the event handlers we need.
*/
Telegram.WebApp.onEvent('themeChanged', function() {
document.getElementById('theme_data').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
});
if (DemoApp.initDataUnsafe.query_id) {
document.getElementById('main_btn').style.display = 'block';
}
document.getElementById('with_webview_btn').style.display = !!DemoApp.initDataUnsafe.query_id && !DemoApp.initDataUnsafe.receiver ? 'block' : 'none';
document.getElementById('webview_data').innerHTML = JSON.stringify(DemoApp.initDataUnsafe, null, 2);
document.getElementById('theme_data').innerHTML = JSON.stringify(Telegram.WebApp.themeParams, null, 2);
document.getElementById('regular_link').setAttribute('href', document.getElementById('regular_link').getAttribute('href') + location.hash);
document.getElementById('text_field').focus();
document.getElementById('regular_field').addEventListener('input', function(e) {
const val = this.value.toLowerCase();
if (val.indexOf('progress') >= 0) {
Telegram.WebApp.MainButton.showProgress();
} else {
Telegram.WebApp.MainButton.hideProgress();
}
});
document.getElementById('ver').innerHTML = Telegram.WebApp.version;
document.getElementById('platform').innerHTML = Telegram.WebApp.platform;
if (DemoApp.initDataUnsafe.receiver) {
document.getElementById('peer_wrap').style.display = 'block';
document.getElementById('peer_name').innerHTML = DemoApp.initDataUnsafe.receiver.first_name + ' ' + DemoApp.initDataUnsafe.receiver.last_name;
if (DemoApp.initDataUnsafe.receiver.photo_url) {
document.getElementById('peer_photo').setAttribute('src', DemoApp.initDataUnsafe.receiver.photo_url);
} else {
document.getElementById('peer_photo').style.display = 'none';
}
} else if (DemoApp.initDataUnsafe.chat) {
document.getElementById('peer_wrap').style.display = 'block';
document.getElementById('peer_name').innerHTML = DemoApp.initDataUnsafe.chat.title;
if (DemoApp.initDataUnsafe.chat.photo_url) {
document.getElementById('peer_photo').setAttribute('src', DemoApp.initDataUnsafe.chat.photo_url);
} else {
document.getElementById('peer_photo').style.display = 'none';
}
}
DemoApp.checkInitData();
DemoApp.init();
function setViewportData() {
document.querySelector('.viewport-border')
.setAttribute('text', window.innerWidth + ' x ' + round(Telegram.WebApp.viewportHeight, 2))
document.querySelector('.viewport-stable_border')
.setAttribute('text', window.innerWidth + ' x ' + round(Telegram.WebApp.viewportStableHeight, 2) +
' | is_expanded: ' + (Telegram.WebApp.isExpanded ? 'true' : 'false'));
}
Telegram.WebApp.setHeaderColor('secondary_bg_color');
Telegram.WebApp.onEvent('viewportChanged', setViewportData);
setViewportData();
Telegram.WebApp.onEvent('settingsButtonClicked', function() {
alert('Settings opened!');
});
let prevBgColorVal = document.getElementById('bg_color_sel').value;
const bgColorInput = document.getElementById('bg_color_input');
const headerColorSel = document.getElementById('header_color_sel');
bgColorInput.value = Telegram.WebApp.backgroundColor;
document.body.setAttribute('style', '--bg-color:' + Telegram.WebApp.backgroundColor);
headerColorSel.value = 'secondary_bg_color';
headerColorSel.addEventListener('change', function(e) {
const colorKey = e.target.value;
document.getElementById('top_sect').classList.toggle('second', colorKey === 'secondary_bg_color');
Telegram.WebApp.setHeaderColor(colorKey);
document.body.setAttribute('style', '--bg-color:' + Telegram.WebApp.backgroundColor);
});
bgColorInput.addEventListener('change', function(e) {
const color = e.target.value;
document.getElementById('bg_color_val').textContent = color;
headerColorSel.value = 'custom';
prevBgColorVal = document.getElementById('bg_color_sel').value;
Telegram.WebApp.setBackgroundColor(color);
document.body.setAttribute('style', '--bg-color:' + Telegram.WebApp.backgroundColor);
});
headerColorSel.addEventListener('change', function(e) {
const colorKey = e.target.value;
if (colorKey === 'custom') {
headerColorSel.value = prevBgColorVal;
bgColorInput.focus();
} else {
document.getElementById('bg_color_val').textContent = 'custom...';
Telegram.WebApp.setBackgroundColor(colorKey);
document.body.setAttribute('style', '--bg-color:' + Telegram.WebApp.backgroundColor);
bgColorInput.value = Telegram.WebApp.backgroundColor;
prevBgColorVal = headerColorSel.value;
}
});
Telegram.WebApp.onEvent('themeChanged', function() {
bgColorInput.value = Telegram.WebApp.backgroundColor;
document.body.setAttribute('style', '--bg-color:' + Telegram.WebApp.backgroundColor);
});
DemoApp.testClipboard(document.getElementById('clipboard_test'));
</script>
</body>
</html>