Skip to content

Instantly share code, notes, and snippets.

@evtuhovdo
Last active May 9, 2021 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evtuhovdo/c3f8b2cc5894c9b693153683ec32e2d5 to your computer and use it in GitHub Desktop.
Save evtuhovdo/c3f8b2cc5894c9b693153683ec32e2d5 to your computer and use it in GitHub Desktop.
QR scan frappe
#preview {
display: none;
}
#preview.active {
width: 100vw;
top: 0;
left: 0;
position: fixed;
display: block;
}
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://unpkg.com/@zxing/library@latest";
script.async = false;
head.appendChild(script);
var video = document.createElement('video');
video.id = 'preview';
var activeInput = null;
// var videoButton = document.createElement('button');
// videoButton.id = 'video_button';
$(function () {
$('form').append(video);
var codeReader;
var selectedDeviceId;
script.addEventListener('load', function () {
codeReader = new ZXing.BrowserMultiFormatReader();
});
function stop() {
$('#preview').removeClass('active');
codeReader.reset();
}
var allDevices = [];
var selectedDeviceIndex = null;
function start() {
console.log('ZXing code reader initialized')
codeReader.listVideoInputDevices()
.then(function (videoInputDevices) {
allDevices = videoInputDevices;
if (selectedDeviceIndex === null) {
selectedDeviceIndex = allDevices.length - 1;
}
selectedDeviceId = videoInputDevices[selectedDeviceIndex].deviceId;
codeReader.decodeFromVideoDevice(selectedDeviceId, 'preview', (result, err) => {
if (result) {
console.log('result', result);
activeInput.val(result.text);
stop();
// console.log(result)
// document.getElementById('result').textContent = result.text
}
if (err && !(err instanceof ZXing.NotFoundException)) {
alert(err);
stop();
// document.getElementById('result').textContent = err
}
})
console.log(`Started continous decode from camera with id ${selectedDeviceId}`)
})
.catch((err) => {
console.error(err)
});
}
$('input[data-fieldname^="cqr"], input[data-fieldname^="cQR"]').each(function () {
var $this = $(this);
$this.attr('disabled', 'disabled');
var button = document.createElement('button');
button.className = 'btn btn-primary btn-sm ml-2';
button.innerHTML = 'Scan';
button.onclick = function () {
activeInput = $this;
$('#preview').addClass('active');
start();
}
$(this).parents('.control-input').eq(0).addClass('flex');
$(this).parents('.control-input').eq(0).append(button);
});
$('body').on('click', 'video#preview', function () {
if (allDevices.length > 0) {
var newIndex = selectedDeviceIndex + 1;
if (newIndex < allDevices.length) {
selectedDeviceIndex = newIndex;
} else {
selectedDeviceIndex = 0;
}
start();
}
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment