davidshimjs / qrcodejs

Cross-browser QRCode generator for javascript
MIT License
13.62k stars 4.76k forks source link

img src is empty and canvas is visible on Android #287

Open akinuri opened 1 year ago

akinuri commented 1 year ago

I see that the QR code is generated on canvas, and then copied to an img element using base64 and the canvas is hidden.

This process does not seem to work properly on Android. The canvas is visible (but should be hidden), and the src attribute of the img is empty, which gives the impression that the image is hidden. However, it works as expected on iOS.

Tested this on the following devices/browsers:

I had to figure out a way to show the QR (and style the canvas and the image the same) on both desktop and mobile.

The code I used to test this out:

<style>
    #qrcode canvas { border: 5px solid red; }
    #qrcode img    { border: 5px solid limegreen; }
</style>

<div id="qrcode"></div>

<script src="qrcode.min.js"></script>

<script type="text/javascript">
new QRCode(document.getElementById("qrcode"), "http://jindo.dev.naver.com/collie");
</script>

On desktop, I see the green one. On mobile, it's the red one.

akinuri commented 1 year ago

I figured out what the problem is when I took a quick look at the source code.

The following function assumes the user agent string will include only decimal numbers and that the integer will be only single digit. So when it encounters the Android 12 string in the ua, it fails.

function _getAndroid() {
    var android = false;
    var sAgent = navigator.userAgent;
    if (/android/i.test(sAgent)) { // android
        android = true;
        var aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i);
        if (aMat && aMat[1]) {
            android = parseFloat(aMat[1]);
        }
    }
    return android;
}

The regex pattern is poor. Instead it should be /android ([0-9]+(?:\.[0-9]+)?)/i. With this change, it works as expected.

Might do a PR later.

akinuri commented 1 year ago

Ah, there's already an open PR (https://github.com/davidshimjs/qrcodejs/pull/226) related to this. Although, that pattern has a minor issue too.