-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathindex.html
801 lines (710 loc) · 27.2 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
<!doctype html>
<html lang="en">
<head>
<title>2FA QR Code Generator</title>
<meta charset="utf-8">
<meta name="author" content="Stefan Sundin">
<meta name="description" content="2FA QR Code Generator">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com; font-src https://fonts.gstatic.com; img-src 'self' data:; manifest-src 'self'; worker-src 'self'">
<link rel="icon">
<link rel="manifest" href="app.webmanifest">
<link rel="license" href="https://www.gnu.org/licenses/gpl-3.0.html" title="GNU GPL 3.0 or later">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:500,400">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/kjua.min.js" integrity="sha256-U9OwIwkuBJSExOOc5vUNG43RAHR5XmbaBuEUB5KpHZo=" crossorigin="anonymous"></script>
<style>
body {
margin-bottom: 100px;
}
@media (min-width: 768px) {
.container {
max-width: 770px;
}
}
header {
text-align: center;
}
h1 {
font-size: 4em;
font-weight: 700;
}
h2 {
font-size: 1.5em;
font-weight: 400;
}
input:invalid {
border-color: #dc3545;
}
a[data-bs-toggle="modal"] {
color: #007bff !important;
cursor: pointer;
}
a[data-bs-toggle="modal"]:hover {
text-decoration: underline !important;
}
.modal.show {
display: block;
}
body.modal-open #qr {
visibility: hidden;
}
#qrdetector_video {
max-width: 75%;
}
#uri {
color: gray;
}
#uri:focus {
color: inherit;
}
#app {
padding: 10px 20px;
background-color: white;
border-top: 15px solid #f2f2f2;
border-bottom: 15px solid #f2f2f2;
font-family: 'Roboto', sans-serif;
}
#app_code {
color: #4285f4;
font-weight: 500;
font-size: xx-large;
}
#app_label {
color: #757575;
}
</style>
</head>
<body>
<header class="mt-4">
<h1 itemprop="name">2FA QR Code Generator</h1>
<h2 itemprop="description">Save your 2FA secrets, then use this to scan them again.</h2>
</header>
<div id="container" class="container">
<hr>
<p>This is a 2FA QR code generator made in JavaScript that helps you make QR codes from 2FA secrets. Most websites give you both a QR code and an option to manually type the secret. If you need to decode a QR code to obtain the secret, <a data-bs-toggle="modal" data-bs-target="#qrdetector_modal" id="open_qrdetector">click here</a>. To use this app offline, <a data-bs-toggle="modal" data-bs-target="#service_worker_modal">click here</a>.</p>
<noscript>
<div class="alert alert-danger text-center font-weight-bold" role="alert">
This page requires JavaScript.
</div>
</noscript>
<div class="modal" id="qrdetector_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Scan QR code</h5>
</div>
<div class="modal-body" id="qrdetector_body_loading">
<div class="alert alert-info" role="alert" id="qrdetector_loading">Loading..</div>
</div>
<div class="modal-body d-none" id="qrdetector_body">
<input class="d-none" type="file" id="input_file" accept="image/*">
<p>Drag and drop an image, or paste an image or a base64 data URI.</p>
<div class="mb-3">
<button class="btn btn-primary mb-2 me-2" id="btn_file">Select file</button>
<button class="btn btn-primary mb-2 me-2" id="btn_webcam">Capture from webcam</button>
<button class="btn btn-primary mb-2 me-2" id="btn_screen_capture">Capture from screen</button>
<button class="btn btn-danger mb-2 me-2 d-none" id="btn_stop_video">Stop</button>
</div>
<div class="text-center mb-3 d-none" id="qrdetector_video_container">
<video id="qrdetector_video" autoplay muted playsinline controlslist="nofullscreen nodownload disablepictureinpicture"></video>
</div>
<div class="alert alert-info" role="alert" id="qrdetector_status"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" id="btn_close_modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" id="service_worker_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Offline</h5>
</div>
<div class="modal-body">
<p>Installing a service worker makes this page available offline. You can also add the page to your home screen <a href="https://developer.mozilla.org/en-US/docs/Web/API/BeforeInstallPromptEvent/prompt#browser_compatibility">on certain platforms</a>.</p>
<button class="btn btn-primary mb-2 me-2" id="install_service_worker" autocomplete="off" disabled>Install service worker</button>
<button class="btn btn-primary mb-2 me-2" id="a2hs" autocomplete="off" disabled>Add to home screen</button>
<div class="alert alert-danger" role="alert" id="service_worker_alert">
Service workers are not supported by your web browser.
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal-backdrop show d-none" id="modal_backdrop"></div>
<hr>
<p>
<select class="form-select" id="type" autocomplete="off">
<option value="totp">Time based (TOTP)</option>
<option value="hotp">Counter based (HOTP)</option>
</select>
</p>
<p><input class="form-control" type="search" id="secret" placeholder="Secret — Required" autocomplete="off" spellcheck="false"></p>
<p><input class="form-control" type="search" id="label" placeholder="Label — Required" autocomplete="off" spellcheck="false"></p>
<p><input class="form-control" type="search" id="issuer" placeholder="Issuer — Optional" list="issuers" spellcheck="false"></p>
<p><input class="form-control d-none" type="search" id="counter" placeholder="Initial counter — Defaults to 0" pattern="\d+" autocomplete="off" spellcheck="false"></p>
<div class="form-check">
<input class="form-check-input" type="checkbox" id="advanced_options"><label class="form-check-label" for="advanced_options">Advanced options</label>
</div>
<div class="d-none" id="advanced_options_container">
<p>Please note that the advanced options are not supported by the Google Authenticator app (all advanced options are ignored). Yubico Authenticator supports these advanced options.</p>
<p>
<select class="form-select" id="algorithm" autocomplete="off">
<option value="SHA1">SHA1 algorithm (Default)</option>
<option value="SHA256">SHA256 algorithm</option>
<option value="SHA512">SHA512 algorithm</option>
</select>
</p>
<p>
<select class="form-select" id="digits" autocomplete="off">
<option value="6">6 digits (Default)</option>
<option value="8">8 digits</option>
</select>
</p>
<p><input class="form-control" type="search" id="period" placeholder="Valid period, in seconds — Defaults to 30" pattern="\d+" autocomplete="off" spellcheck="false"></p>
</div>
<hr>
<p><input class="form-control" type="text" id="uri" placeholder="otpauth://" autocomplete="off" spellcheck="false"></p>
<datalist id="issuers">
<option>Amazon</option>
<option>Apple</option>
<option>AWS</option>
<option>Blizzard</option>
<option>Cloudflare</option>
<option>Coinbase</option>
<option>DigitalOcean</option>
<option>Discord</option>
<option>Docker</option>
<option>DreamHost</option>
<option>Dropbox</option>
<option>EA</option>
<option>eBay</option>
<option>Epic Games</option>
<option>EVE Online</option>
<option>Evernote</option>
<option>Facebook</option>
<option>Fastly</option>
<option>Firefox</option>
<option>GitHub</option>
<option>GitLab</option>
<option>GoDaddy</option>
<option>Google</option>
<option>Heroku</option>
<option>Humble Bundle</option>
<option>LastPass</option>
<option>MailChimp</option>
<option>Mailgun</option>
<option>MaxCDN</option>
<option>Microsoft</option>
<option>Namecheap</option>
<option>Newegg</option>
<option>npm</option>
<option>Okta</option>
<option>Private Internet Access</option>
<option>ProtonMail</option>
<option>Reddit</option>
<option>Ring</option>
<option>Salesforce</option>
<option>SendGrid</option>
<option>Slack</option>
<option>SparkPost</option>
<option>Threat Stack</option>
<option>Ting</option>
<option>Twitch</option>
<option>Ubisoft</option>
<option>Ubuntu</option>
<option>Yahoo!</option>
</datalist>
<input class="w-100" type="range" id="size" value="200" min="50" max="650" step="25" title="QR Code Size" autocomplete="off">
<div class="p-4 text-center" id="qr"><canvas></div>
<hr>
<p>In the Google Authenticator app, it will look something like this:</p>
<div id="app">
<div id="app_code">123 456</div>
<div id="app_label">Issuer (label)</div>
</div>
<hr>
<ul>
<li>Made by <a href="https://stefansundin.github.io/">Stefan Sundin</a>.</li>
<li>Get <a href="https://github.com/stefansundin/2fa-qr">the source code</a>.</li>
<li>Uses <a href="https://github.com/lrsjng/kjua">kjua</a> and <a href="https://github.com/stefansundin/qr-detector.js">QrDetector</a>.</li>
<li>See <a href="https://github.com/google/google-authenticator/wiki/Key-Uri-Format">the docs</a> for the URI format.</li>
<li>Download an offline version <a href="https://github.com/stefansundin/2fa-qr/archive/refs/heads/offline.zip">here</a>.</li>
</ul>
</div>
<script>
// generate a nice QR code for the favicon
const el = kjua({
crisp: false,
render: "image",
text: "stefansundin"
});
document.querySelector("link[rel=icon]").href = el.getAttribute("src");
const container = document.getElementById("container");
const type = document.getElementById("type");
const secret = document.getElementById("secret");
const label = document.getElementById("label");
const issuer = document.getElementById("issuer");
const counter = document.getElementById("counter");
const advanced_options = document.getElementById("advanced_options");
const advanced_options_container = document.getElementById("advanced_options_container");
const algorithm = document.getElementById("algorithm");
const digits = document.getElementById("digits");
const period = document.getElementById("period");
const uri = document.getElementById("uri");
const qr = document.getElementById("qr");
const app_label = document.getElementById("app_label");
function type_changed(e) {
counter.classList.toggle("d-none", type.value !== "hotp");
period.classList.toggle("d-none", type.value !== "totp");
}
function advanced_options_changed() {
advanced_options_container.classList.toggle("d-none", !advanced_options.checked);
}
function generate_uri() {
let s = `otpauth://${type.value}/${encodeURIComponent(label.value)}?secret=${secret.value.replace(/ /g, '')}`;
if (issuer.value !== "") {
s += `&issuer=${encodeURIComponent(issuer.value)}`;
}
if (type.value === "hotp") {
s += `&counter=${counter.value || "0"}`;
}
if (advanced_options.checked) {
s += `&algorithm=${algorithm.value}&digits=${digits.value}`;
if (type.value === "totp") {
s += `&period=${period.value || "30"}`;
}
}
return s;
}
function update_uri() {
const s = generate_uri();
if (s === uri.value) {
return;
}
uri.value = s;
update_qr();
uri.classList.remove("is-invalid");
secret.classList.toggle("is-invalid", secret.value === "");
label.classList.toggle("is-invalid", label.value === "");
}
function update_qr() {
const el = kjua({
crisp: false,
render: 'canvas',
text: uri.value,
size: size.value,
});
qr.replaceChild(el, qr.firstElementChild);
if (label.value === "" && issuer.value === "") {
app_label.textContent = "Issuer (label)";
} else {
app_label.textContent = issuer.value === "" ? label.value : `${issuer.value} (${label.value})`;
}
}
function decode(s) {
return s ? decodeURIComponent(s) : "";
}
// Note: Switch to URL.canParse() in a few years when it is more widely available.
function URLcanParse(url) {
try {
new URL(url);
return true;
} catch (err) {
return false;
}
}
function parse_uri() {
// update the QR code
update_qr();
if (!URLcanParse(uri.value)) {
uri.classList.add("is-invalid");
return;
}
// validate and parse the uri
const url = new URL(uri.value);
// Firefox puts "//totp/" in the pathname, whereas Chrome and Safari puts "totp" in the host
const url_type = url.host || url.pathname.split("/")[2];
let url_label = decode(url.pathname.substr(url.host ? 1 : 7));
if (url.protocol === "otpauth:"
&& (url_type === "totp" || url_type === "hotp")
&& url.searchParams.has("secret")
) {
uri.classList.remove("is-invalid");
} else {
uri.classList.add("is-invalid");
return;
}
const s = generate_uri();
if (s === uri.value) {
// the uri did not change
return;
}
// handle legacy URI format where the issuer used to be prefixed in the label, some programs put the issuer in both places which is annoying
const url_issuer = decode(url.searchParams.get("issuer"));
if (url_label.startsWith(`${url_issuer}:`)) {
url_label = url_label.substr(url_issuer.length + 1);
}
// update fields
const c = url.searchParams.get("counter") || "";
type.value = url_type;
label.value = url_label;
secret.value = url.searchParams.get("secret");
issuer.value = url_issuer;
counter.value = c === "0" ? "": c;
advanced_options.checked = url.searchParams.has("algorithm") || url.searchParams.has("digits") || url.searchParams.has("period");
algorithm.value = url.searchParams.get("algorithm") || "SHA1";
digits.value = url.searchParams.get("digits") || "6";
period.value = url.searchParams.get("period") === "30" ? "": url.searchParams.get("period");
secret.classList.toggle("is-invalid", secret.value === "");
label.classList.toggle("is-invalid", label.value === "");
type_changed();
advanced_options_changed();
}
function resize() {
const old_value = size.value;
size.max = Math.min(650, container.clientWidth - 2*(24+15));
if (size.value !== old_value) {
update_qr();
}
}
[
type, secret, label, issuer, counter,
advanced_options, algorithm, digits, period,
].forEach(el => el.addEventListener("input", update_uri));
type.addEventListener("input", type_changed);
advanced_options.addEventListener("input", advanced_options_changed);
uri.addEventListener("input", parse_uri);
size.addEventListener("input", update_qr);
window.addEventListener("resize", resize);
resize();
update_uri();
// QR Detector feature (loaded on demand)
const open_qrdetector = document.getElementById('open_qrdetector');
const qrdetector_modal = document.getElementById('qrdetector_modal');
const modal_backdrop = document.getElementById('modal_backdrop');
const qrdetector_body_loading = document.getElementById('qrdetector_body_loading');
const qrdetector_loading = document.getElementById('qrdetector_loading');
const qrdetector_body = document.getElementById('qrdetector_body');
const input_file = document.getElementById('input_file');
const btn_file = document.getElementById('btn_file');
const btn_webcam = document.getElementById('btn_webcam');
const btn_screen_capture = document.getElementById('btn_screen_capture');
const btn_stop_video = document.getElementById('btn_stop_video');
const btn_close_modal = document.getElementById('btn_close_modal');
const qrdetector_video = document.getElementById('qrdetector_video');
const qrdetector_video_container = document.getElementById('qrdetector_video_container');
const qrdetector_status = document.getElementById('qrdetector_status');
// Open and close bootstrap modals without bootstrap js
function open_modal(element) {
element.classList.add('show');
modal_backdrop.classList.remove('d-none');
document.body.classList.add('modal-open');
}
function close_modal(element) {
element.classList.remove('show');
modal_backdrop.classList.add('d-none');
document.body.classList.remove('modal-open');
}
for (const btn of document.querySelectorAll('[data-bs-toggle="modal"]')) {
btn.addEventListener('click', function() {
open_modal(document.querySelector(this.dataset.bsTarget));
});
}
for (const btn of document.querySelectorAll('[data-bs-dismiss="modal"]')) {
btn.addEventListener('click', function() {
let element = this;
while (element = element.parentElement) {
if (element.classList.contains('modal')) {
close_modal(element);
break;
}
}
});
}
for (const modal of document.querySelectorAll('.modal')) {
modal.addEventListener('click', function(e) {
if (e.target === this) {
const btn = this.querySelector('[data-bs-dismiss="modal"]');
if (btn) {
btn.click();
} else {
close_modal(this);
}
}
});
}
open_qrdetector.addEventListener('click', async () => {
qrdetector_status.textContent = 'Waiting for image..';
qrdetector_status.className = 'alert alert-info';
if (window.QrDetector) {
return;
}
function stop_video() {
qrdetector_video_container.classList.add('d-none');
btn_stop_video.classList.add('d-none');
if (!qrdetector_video.srcObject) {
return;
}
qrdetector_video.srcObject.getTracks().forEach(track => track.stop());
qrdetector_video.srcObject = null;
}
btn_close_modal.addEventListener('click', () => stop_video());
function qrdetector_ready() {
qrdetector_body_loading.classList.add('d-none');
qrdetector_body.classList.remove('d-none');
const detector = new QrDetector({ formats: ['qr_code'] });
async function handle_file(file) {
if (!file) {
return;
}
try {
if (file instanceof File) {
file = await createImageBitmap(file);
}
const results = await detector.detect(file);
console.log(results);
if (results.length === 0) {
qrdetector_status.textContent = 'A QR code was not detected in the image.';
qrdetector_status.className = 'alert alert-warning';
return;
}
for (r of results) {
if (!r.rawValue.startsWith('otpauth://')) {
console.warn('Unsupported URI', r.rawValue);
continue;
}
uri.value = r.rawValue;
parse_uri();
update_qr();
if (secret.value === '') {
continue;
}
btn_close_modal.click();
return;
}
qrdetector_status.textContent = 'The QR code data does not start with "otpauth://".';
qrdetector_status.className = 'alert alert-warning';
} catch (e) {
console.error(e);
qrdetector_status.textContent = `Error: ${e}`;
qrdetector_status.className = 'alert alert-danger';
}
}
function process_video_frame() {
requestAnimationFrame(async () => {
if (!qrdetector_video.src && !qrdetector_video.srcObject) {
return;
}
if (qrdetector_video.readyState <= 1) {
process_video_frame();
return;
}
try {
const results = await detector.detect(qrdetector_video);
if (results.length > 0) {
for (r of results) {
if (!r.rawValue.startsWith('otpauth://')) {
continue;
}
uri.value = r.rawValue;
parse_uri();
update_qr();
if (secret.value === '') {
continue;
}
btn_close_modal.click();
return;
}
qrdetector_status.textContent = 'The QR code data does not start with "otpauth://".';
qrdetector_status.className = 'alert alert-warning';
}
} catch (e) {
console.error(e);
}
if (!qrdetector_video.paused && !qrdetector_video.ended) {
process_video_frame();
}
});
};
input_file.addEventListener('change', async e => {
for (const file of e.target.files) {
handle_file(file);
}
});
btn_file.addEventListener('click', () => input_file.click());
btn_webcam.addEventListener('click', async () => {
btn_webcam.blur();
try {
qrdetector_video.srcObject = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment' },
audio: false,
});
qrdetector_video.srcObject.getTracks().forEach(t =>
t.addEventListener('ended', stop_video),
);
qrdetector_video_container.classList.remove('d-none');
btn_stop_video.classList.remove('d-none');
qrdetector_status.textContent = 'Waiting for QR code..';
qrdetector_status.className = 'alert alert-info';
}
catch (e) {
console.error(e);
btn_webcam.classList.add('btn-danger');
qrdetector_status.textContent = e;
qrdetector_status.className = 'alert alert-danger';
return;
}
btn_webcam.classList.remove('btn-danger');
});
btn_screen_capture.addEventListener('click', async () => {
btn_screen_capture.blur();
try {
qrdetector_video.srcObject = await navigator.mediaDevices.getDisplayMedia({
video: {
cursor: 'always',
},
audio: false,
});
qrdetector_video.srcObject.getTracks().forEach(t =>
t.addEventListener('ended', stop_video),
);
qrdetector_video_container.classList.remove('d-none');
btn_stop_video.classList.remove('d-none');
qrdetector_status.textContent = 'Waiting for QR code..';
qrdetector_status.className = 'alert alert-info';
}
catch (e) {
console.error(e);
btn_screen_capture.classList.add('btn-danger');
qrdetector_status.textContent = e;
qrdetector_status.className = 'alert alert-danger';
return;
}
btn_screen_capture.classList.remove('btn-danger');
});
btn_stop_video.addEventListener('click', stop_video);
qrdetector_video.addEventListener('play', () => process_video_frame());
window.addEventListener('dragover', (e) => {
e.preventDefault();
});
window.addEventListener('dragleave', e => {
if (e.relatedTarget) {
return;
}
e.preventDefault();
});
window.addEventListener('drop', (e) => {
e.preventDefault();
if (e.dataTransfer.items) {
for (const item of e.dataTransfer.items) {
if (item.kind !== 'file') {
continue;
}
handle_file(item.getAsFile());
}
}
});
window.addEventListener('paste', e => {
e.preventDefault();
for (const item of e.clipboardData.items) {
if (item.kind === 'string') {
// Check if pasting a data URI
const text = e.clipboardData.getData('text/plain');
if (text.startsWith('data:image/')) {
const img = new Image();
img.addEventListener('load', () => handle_file(img));
img.src = text;
}
continue;
}
if (item.kind !== 'file') {
continue;
}
if (item.type.startsWith('image/')) {
handle_file(item.getAsFile());
} else if (item.type === 'text/plain') {
// Check if pasting a text file that contains a data URI
// This does not work well in Firefox
const reader = new FileReader();
reader.addEventListener('load', () => {
const text = reader.result;
if (text.startsWith('data:image/')) {
const img = new Image();
img.addEventListener('load', () => handle_file(img));
img.src = text;
}
});
reader.readAsText(item.getAsFile());
} else {
console.warn('Unknown file type');
}
}
});
}
// Use the built-in BarcodeDetector if possible, but this is not widely supported yet
if (window.BarcodeDetector) {
const supportedFormats = await BarcodeDetector.getSupportedFormats();
if (supportedFormats.includes('qr_code')) {
window.QrDetector = BarcodeDetector;
qrdetector_ready();
return;
}
}
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/gh/stefansundin/[email protected]/dist/QrDetector.min.js';
script.integrity = 'sha384-q+KgD6lkhr01XgU0YB6XB3vs+ufU5/DnQ4oRuxx0qG9lpuSUkWgurNXr86DBJIx5';
script.crossOrigin = 'anonymous';
script.addEventListener('load', qrdetector_ready);
script.addEventListener('error', () => {
qrdetector_loading.textContent = 'An error occurred while loading the QR detection library. Please check the browser console for errors.';
qrdetector_loading.className = 'alert alert-danger';
});
document.head.appendChild(script);
});
if (navigator.serviceWorker && document.location.protocol === 'https:') {
const service_worker_alert = document.getElementById('service_worker_alert');
service_worker_alert.classList.add('d-none');
const install_service_worker = document.getElementById('install_service_worker');
install_service_worker.disabled = false;
async function refresh_service_worker_info() {
const all_registrations = await navigator.serviceWorker.getRegistrations();
const installed = all_registrations.some(r => window.location.href.startsWith(r.scope));
install_service_worker.textContent = `${installed ? 'Uninstall' : 'Install'} service worker`;
}
refresh_service_worker_info();
install_service_worker.addEventListener('click', async e => {
e.preventDefault();
const all_registrations = await navigator.serviceWorker.getRegistrations();
const registrations = all_registrations.filter(r => window.location.href.startsWith(r.scope));
if (registrations.length > 0) {
for (const registration of registrations) {
await registration.unregister();
}
await caches.delete('2fa-qr');
} else {
await navigator.serviceWorker.register('sw.js');
}
refresh_service_worker_info();
});
}
let deferred_prompt;
const btn_a2hs = document.getElementById('a2hs');
btn_a2hs.addEventListener('click', () => {
btn_a2hs.disabled = true;
deferred_prompt.prompt();
});
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault();
deferred_prompt = e;
btn_a2hs.disabled = false;
});
</script>
</body>
</html>