How to include Include QR & Bar code scanner using HTML and JavaScript
1) Scanning QR Codes and Bar codes are sometimes necessary in our E-commerce websites or admin panel
2) In this discussion we will see how we can include such scanner in our website
3) Include the following CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.4/html5-qrcode.min.js" integrity="sha512-k/KAe4Yff9EUdYI5/IAHlwUswqeipP+Cp5qnrsUjTPCgl51La2/JhyyjNciztD7mWNKLSXci48m7cctATKfLlQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body data-rsssl=1>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html5-qrcode/2.3.4/html5-qrcode.min.js"
integrity="sha512-k/KAe4Yff9EUdYI5/IAHlwUswqeipP+Cp5qnrsUjTPCgl51La2/JhyyjNciztD7mWNKLSXci48m7cctATKfLlQ=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
main {
display: flex;
justify-content: center;
align-items: center;
}
#reader {
width: 600px;
}
#result {
text-align: center;
font-size: 1.5rem;
}
</style>
<main>
<div id="reader"></div>
<div id="result"></div>
</main>
<script>
const scanner = new Html5QrcodeScanner('reader', {
qrbox: {
width: 250,
height: 250,
},
fps: 20,
});
//Handle the success result here
scanner.render(success, error);
function success(result) {
document.getElementById('result').innerHTML = `
<h2>Success!</h2>
<p><a href="${result}">${result}</a></p>
`;
scanner.clear();
document.getElementById('reader').remove();
}
function error(err) {
console.error(err);
}
</script>
</body>
</html>
4) Further you can style the view by editing the js file which we are included from CDN
5) The scanned result will be shown with the success message and a redirect URL, further you can include any backend functionality using ajax to handle the redirects.
By following the above code we can integrate a qr/bar code scanner in our website