Skip to content

Instantly share code, notes, and snippets.

@mebjas
Last active September 27, 2023 06:22
  • Star 16 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Demo code on using github.com/mebjas/html5-qrcode. This was used in https://blog.minhazav.dev/research/html5-qrcode.html
<html>
<head>
<title>Html-Qrcode Demo</title>
<body>
<div id="qr-reader" style="width:500px"></div>
<div id="qr-reader-results"></div>
</body>
<script src="https://raw.githubusercontent.com/mebjas/html5-qrcode/master/minified/html5-qrcode.min.js"></script>
<script src="html5-qrcode-demo.js"></script>
</head>
</html>
function docReady(fn) {
// see if DOM is already available
if (document.readyState === "complete" || document.readyState === "interactive") {
// call on next available tick
setTimeout(fn, 1);
} else {
document.addEventListener("DOMContentLoaded", fn);
}
}
docReady(function() {
var resultContainer = document.getElementById('qr-reader-results');
var lastResult, countResults = 0;
var html5QrcodeScanner = new Html5QrcodeScanner(
"qr-reader", { fps: 10, qrbox: 250 });
function onScanSuccess(decodedText, decodedResult) {
if (decodedText !== lastResult) {
++countResults;
lastResult = decodedText;
console.log(`Scan result = ${decodedText}`, decodedResult);
resultContainer.innerHTML += `<div>[${countResults}] - ${decodedText}</div>`;
// Optional: To close the QR code scannign after the result is found
html5QrcodeScanner.clear();
}
}
// Optional callback for error, can be ignored.
function onScanError(qrCodeError) {
// This callback would be called in case of qr code scan error or setup error.
// You can avoid this callback completely, as it can be very verbose in nature.
}
html5QrcodeScanner.render(onScanSuccess, onScanError);
});
@Haz-MatPLz
Copy link

because I'm using it in one of my clients apps and was wondering how to make (no offence meant hear) not so ugly

@Haz-MatPLz
Copy link

@mebjas plz read the above

@mebjas
Copy link
Author

mebjas commented Oct 10, 2020

@Haz-MatPLz - Html5QrcodeScanner is meant to provide a simple UI experience for QR code scanning. If you want to use your own UI, use Html5Qrcode library which provides all the necessary APIs to build so.

Reference: https://github.com/mebjas/html5-qrcode#for-using-inline-qr-code-scanning-with-webcam-or-smartphone-camera

@charmjo
Copy link

charmjo commented Nov 20, 2020

I'm glad that I was able to find this sample and opted for the end-to-end scanner. Is there a way to turn off the camera (from scanning to idle again) if it doesn't successfully scan for a certain amount of time?

@virtualvoid
Copy link

virtualvoid commented Dec 14, 2020

not working on iOS, permissions denied.

edit: the website needs to be on HTTPS

@hasalfernando
Copy link

image

Does anyone know whether there is any possible solution to change the default width of video from 300px? Though I have set the width of div to 100%, video and canvas width of 300px is being overridden and video is getting cornered to the left. I want to know whether there is any possible way to adjust this width?

@virtuosodelared
Copy link

@matiazar If I recall correctly this can be achieved when you use the Html5Qrcode directly. In the demo I have consciously added logic for request permission every time - to both show demo and I think user should have control.

But at the API level, the permission is needed only once* (...)

Thanks for this great applicaction. I am using this qr reader in a pc with a webcam to read qrcodes, open urls from qr´s, and back again to the qr reader. So I would like to know if is possible to avoid give permissions again and also click in "start scanning" button. In this way, qr reader will be scanning automatically.
Please let me know if this is possible and how i can achieve it. Thanks in advance

@jmsousa
Copy link

jmsousa commented Jan 27, 2021

Hi, I am trying to use in Blazor with the following code:

Blazor Page:
<div style="width: auto" id="reader"></div>' @code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) await _jsRuntime.InvokeVoidAsync("Html5QrCode", DotNetObjectReference.Create(this));
await base.OnAfterRenderAsync(firstRender);
}
}
`

Js:
`function Html5QrCode () {
var html5QrCode = new Html5Qrcode("reader");
Html5Qrcode.getCameras().then(devices => {

    if (devices && devices.length) {

        var cameraId = devices[1].id;
        
        alert("cameraId: " + cameraId);

        html5QrCode.start(
            cameraId,
            {
                fps: 10,    // Optional frame per seconds for qr code scanning
                qrbox: 250  // Optional if you want bounded box UI
            },
            qrCodeMessage => {
                // do something when code is read
                alert(qrCodeMessage);
            },
            errorMessage => {
                // parse error, ignore it.
                // alert(errorMessage);
            })
            .catch(err => {
                // Start failed, handle it.
            });
    }
}).catch(err => {
    // handle err
    alert(err);
});

};`

I can read the camera id, but then I have the following error:
Cannot set property 'innerHTML' of null

thanks,
João Sousa

@friendztech7
Copy link

when i run code on phone it's show
error :- unable to query supported devices

Please Help Sir

@Take51
Copy link

Take51 commented Mar 3, 2021

HI,
You code works super good. Anyway I need some help.
When I scanned the QR code, scanner was shutted down and give me a result from the scan.
Can I after this add some button like "Start a new scan" or "Scan another code"? Because now, when I want a new scan, I must reload the whole page..
Thanks,
Dominik

@snatcoinOfficial
Copy link

snatcoinOfficial commented Mar 18, 2021

Nice QR code reader.. but...
Does anyone know what permissions you need to add to Android Studio to get this to work within an Android app (as a webview)? I've added the camera and write external permissions.. but within the app it says "NotAllowedError: Permission denied". Though if I load up the url within Chrome it works fine. (The url is https)

Thanks.

@Reza-kavian
Copy link

In your site demo, in addition to qrcode, I can also scan barcodes. But when I transfer the source code to my project, it only reads qrcode but does not read barcodes

@viney-equinix
Copy link

Hi Everyone,

I am facing the issue with Html5Qrcode availability in global scope in my react typescript app. i am following this article (https://simbathesailor.dev/qrcode-scan-web-reactjs/) to implement as Hook in my react-typescript app, could you please help me to fix this issue. how can i declare in .d.ts file.

What exactly you want to say in below comment
// eslint-disable-next-line
const html5qrCodeScanner = new Html5Qrcode(qrcodeMountNodeID);

How can i fix this issue, i am not getting Html5Qrcode in global scope event after following the complete steps ?

Please help

@haspden
Copy link

haspden commented May 14, 2021

Hi Guys I have a lovely working example setup including some customisations of redirecting the user to a page with variables gathered from the QR code for processing, but I'm still stuck on how to enforce the rear camera...

Posted my general question here but could do with some input
https://stackoverflow.com/questions/67538983/navigator-mediadevices-getusermedia-reverse-camera-list-order-show-only-rear

I think the issue is I am using the simple version and applying my custom js inside resultContainer.innerHTML += and I need to be using the (start) method / PRO method instead, however I cant find any examples of this method?

@mebjas do you have any thoughts

Thanks

@davidcbittner
Copy link

This routine is working for my needs and I have my code in there to process the qrCodeMessage and the .clear() does clear it however wipes the widget completely from the body. What's the procedure to stop scanning once you have success and stop the video feed etc as if you hit the stop button on the demo? I want to scan the code, stop video feed etc, process the message then be able to scan a new code. I can't seem to figure out how to start it again after the .clear() without refreshing the page.

function onScanSuccess(qrCodeMessage) {
// handle on success condition with the decoded message
html5QrcodeScanner.clear();
// ^ this will stop the scanner (video feed) and clear the scan area.
}

@Jalil-Irfan
Copy link

In your site demo, in addition to qrcode, I can also scan barcodes. But when I transfer the source code to my project, it only reads qrcode but does not read barcodes

Yes i too couldnt scan anything except QR

@mebjas
Copy link
Author

mebjas commented Jun 14, 2021

@Reza-kavian @Jalil-Irfan - Try latest version of the library (v2.0.9), it should read different formats listed in the readme.

@sergey-kukosh
Copy link

Hi mebjas
I found the one problem, I ecoded "1" to QR code, and this what I can't scan, it can't decode. Can you tell me where in the library I can see if I can fix it, thank you!
Screenshot 2021-08-05 at 11 08 57

@vyking60
Copy link

vyking60 commented Jan 3, 2022

Hi mebjas,
I am more or less new to web development. I tried your example but I get error:

scan:57 Uncaught ReferenceError: Html5QrcodeScanner is not defined

I have put in Handlebars layout:

<script src="https://unpkg.com/html5-qrcode" type="text/javascript">

and in handlebars view this:

QR Code Scanner

<script> var resultContainer = document.getElementById('qr-reader-results'); var lastResult, countResults = 0; function onScanSuccess(decodedText, decodedResult) { if (decodedText !== lastResult) { ++countResults; lastResult = decodedText; // Handle on success condition with the decoded message. console.log(`Scan result ${decodedText}`, decodedResult); } } var html5QrcodeScanner = new Html5QrcodeScanner( "qr-reader", { fps: 10, qrbox: 250 }); html5QrcodeScanner.render(onScanSuccess); </script>

I know it must be some 'basic' problem... Can you help?

@fopsycute
Copy link

hi mebjas, I tried using all ur format, but anytime I display it on browser(localhost) everything is always blank....no camera showing

@bkmattias
Copy link

Good evening. Is there a way to set it on image reader by default instead of scan first?

@apkc
Copy link

apkc commented Aug 30, 2022

I seem to have an issue when the qrcode scanner is kept in between the

. When the scanner starts it prompts the permission with REQUEST CAMERA PERMISSIONS button. but since the button is not having any type"button" attribute by default, it is posting the form automatically which is unintended. how can the type="button" be added to prevent it? Thanks

@Macof08
Copy link

Macof08 commented Oct 10, 2022

@mwambajoshua for now, you can do this

function validURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ // port and path
    '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string
    '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
  return !!pattern.test(str);
}

function onScanSuccess(qrCodeMessage) {
  if (validURL(qrCodeMessage)) {
    window.location.href = qrCodeMessage;
  }
}

var html5QrcodeScanner = new Html5QrcodeScanner(
	"qr-reader", { fps: 10, qrbox: 250 });
html5QrcodeScanner.render(onScanSuccess);

@mebjas how can i add this script only the back camara? html5QrcodeScanner.render({ facingMode: { exact:"environment" } }, onScanSuccess); i cant :(

@Mbengparis
Copy link

Mbengparis commented Mar 10, 2023

@mebjas please

  • how can i change the text?. For example "Request Camera permission" to be changed to something else.
  • By default when the render is called, there is a "Scan an Image File", how can i remove this?.

@SanSoftInfoTech
Copy link

Nice QR code reader.. but... Does anyone know what permissions you need to add to Android Studio to get this to work within an Android app (as a webview)? I've added the camera and write external permissions.. but within the app it says "NotAllowedError: Permission denied". Though if I load up the url within Chrome it works fine. (The url is https)

Thanks.

are you able to use this in the web view ??

@metechant
Copy link

@mebjas first of all thank you very much for your this lovely project. I have some questions but right before that, I want to tell what I am trying to do. I have an inventory management system website. And while user is adding the product, I want the user to scan qr code as product id and write it into a text box there so it can be saved to mysql with that ID from qr code. For this I have added a button there which is opening a new window with this qr code scanner I do see it is reading the qr code as I can see green corners but I dont know how I can get that code to that text box which is located on the previous page. And also I want this pop up closes automatically after reading the qr code and get back to previous page. How can this be possible. I am also a new developer so it is a bit complicated for me to understand some parts of your project. So can you help me with this with code examples? Or maybe you can advice me an different way to do this instead of a pop up window?

Thank you for your help

@faxilmir
Copy link

faxilmir commented Apr 3, 2023

Nice QR code reader.. but... Does anyone know what permissions you need to add to Android Studio to get this to work within an Android app (as a webview)? I've added the camera and write external permissions.. but within the app it says "NotAllowedError: Permission denied". Though if I load up the url within Chrome it works fine. (The url is https)

Thanks.

Hey did you find any solution? I am still looking for the answer?

@faxilmir
Copy link

faxilmir commented Apr 3, 2023

Nice QR code reader.. but... Does anyone know what permissions you need to add to Android Studio to get this to work within an Android app (as a webview)? I've added the camera and write external permissions.. but within the app it says "NotAllowedError: Permission denied". Though if I load up the url within Chrome it works fine. (The url is https)
Thanks.

are you able to use this in the web view ??

Hey did you find any solution? I am so confused.

I believe it has nothing to do with Android Studio, this plugin is somehow not interacting with the Web View. Still looking for answers.

@zeikman
Copy link

zeikman commented Apr 5, 2023

Nice QR code reader.. but... Does anyone know what permissions you need to add to Android Studio to get this to work within an Android app (as a webview)? I've added the camera and write external permissions.. but within the app it says "NotAllowedError: Permission denied". Though if I load up the url within Chrome it works fine. (The url is https)

Thanks.

I am facing the same issue and having little progress with the solution provided here > https://stackoverflow.com/a/61609282/4679429

Basically you also need to further grant the camera permission {RESOURCE_VIDEO_CAPTURE} within webview. Include following code in the WebChromeClient().

@OverRide
public void onPermissionRequest(final PermissionRequest request) {
final String[] requestedResources = request.getResources();
for (String r : requestedResources) {
if (r.equals(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) {
request.grant(new String[]{PermissionRequest.RESOURCE_VIDEO_CAPTURE});
break;
}
}
}

It open the camera successfully now but then another issue comes, which is the camera view won't move (freeze) when I moving the phone and the camera view only update when I touch any place on phone screen. Does anyone has idea on this issue ?


Updated:

I found the solution for the aforementioned issue (camera freeze), basically just need to add an animated SVG into the background of the camera to keep the android webview updated > mebjas/html5-qrcode#659

@sk24jsr
Copy link

sk24jsr commented Sep 27, 2023

hi bro thanks for the solution but need one more help its working only in localhost and Https its not working on http please help
please see the snipe

help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment