Extracting source attribute of generated img by qrcode.js Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Extracting source attribute of generated img by qrcode.js without wasting too much if your time.

The question is published on by Tutorial Guruji team.

Like I said in the title, my problem is that I get an empty string back.

I’m jusing qrcode.js from https://github.com/davidshimjs/qrcodejs .

My Code:

    <script src="qrcode.js"></script>
<div id="qr"></div>

<img id="test" src="https://www.google.de/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">


<script type="text/javascript">
var qrCode = new QRCode(
    document.getElementById('qr'),
    {
        text: 'www.google.de',
        width: 150,
        height: 150,
        onSuccess: (value) => {
            console.log('value',value);
        }
    }
);

</script>

<script>
var test = document.getElementById("test").src;
console.log(test);
var base64 = document.getElementById("qr_neu").src;
console.log(base64);
console.log(typeof base64);
console.log(base64.length);
var dom = document.getElementById("qr_neu").attributes;
console.log(dom);
var code = dom[3];
console.log(code);
</script>

The generated QR-Code works fine and in the developer settings in chrome i can see the src of both

Screenshot: console in chrome

Now I don’t understand wha I can’t access to the src attribute of the qr-code but on the google img.

I also tried the callbackversion descriped on the github issues section but it doesn’t work either. All i want is the base64 code as var for ther applications.

Thanks for helping!

Answer

The reason why you get an empty string back, even though you can see the src value in your dev tools, is that it takes a very short amount of time to generate the QR-Code.

So var base64 = document.getElementById("qr_neu").src;is called before the QR-Code is generated.

Here is a relevant issues on the qrcode.js repository: https://github.com/davidshimjs/qrcodejs/issues/160.

Here is the solution adapted to your code:

const qrDiv = document.getElementById('qr')
var qrCode = new QRCode(
    qrDiv,
    {
        text: 'www.google.de',
        width: 150,
        height: 150,
        onSuccess: (value) => {
            console.log('value',value);
        }
    }
);
const src = qrDiv.children[0].toDataURL("image/png");
console.info(src);
We are here to answer your question about Extracting source attribute of generated img by qrcode.js - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji