Home > front end >  Uncaught TypeError: Cannot read properties of null (reading 'src') while trying to downloa
Uncaught TypeError: Cannot read properties of null (reading 'src') while trying to downloa

Time:01-12

Hello i am creating an Qrcode generator, that after getting generated, i want to download it. i was able to use this code, and it worked at first, however i added a lot more code in my project, and it stopped working, with me getting this error

(index):337 Uncaught TypeError: Cannot read properties of null (reading 'src')
    at downloadcode ((index):337:51)
    at HTMLButtonElement.onclick ((index):74:91)

This is the html where my qrcode is generated, and the button where my click function is

 <!-- Div criada para criar o qrcode 1000x1000 que será utilizado no download, não sendo visivel
      na pagina-->
      <div id="download" style="display: none;"></div>


      <button disabled id="download_button"  onclick="downloadcode()">
        Descarregar QR code
      </button>

This is my downloadcode method

  // Função que faz o download do qrcode em jpg
    function downloadcode() {

      var link = document.createElement("a");
      link.download = "qrcode.jpg";



      var teste = document.getElementById("download");


      link.href = teste.querySelector('img').src;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);


    }

This is how i make my QrCode (using easyqrcode.js) i don't think this is the matter, because i tried generate, like i was when it worked, but unfortunately this time hasn't worked, but i put it here anyway

var options_download = {
        text: texto,
        width: 1000,
        height: 1000,
        colorDark: $('input[name="favcolor"]').val(),
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,

        logoWidth: 475, // fixed logo width. default is `width/3.5`
        logoHeight: 475, // fixed logo height. default is `heigth/3.5`
        logo: imagem, // Relative address, relative to `easy.qrcode.min.js`
        logoBackgroundColor: '#fffff', // Logo backgroud color, Invalid when `logBgTransparent` is true; default is '#ffffff'
        logoBackgroundTransparent: false, // Whether use transparent image, default is false

      }

      new QRCode(document.getElementById("download"),options_download);

I understand that the error is saying that teste.querySelector('img').src is null, but i can't understand why, since it worked before (with the same code for the download function and the htlm)

Thank you in advance

Edit: to explain more what i am trying to do. I generate a QRcode , that appears on my Div with the ID = download, and then by clicking in the download button, i want to download it. Even without using img tags, it was working i added my complete html


      <div >
        <button  onclick="openForm(event, 'telephone')">Contacto</button>
        <button  onclick="openForm(event, 'email')">Email</button>
        <button  onclick="openForm(event, 'url')">Website</button>
        <button  onclick="openForm(event, 'maps')">Localização</button>
        <button  onclick="openForm(event, 'personal')">Personalizado</button>
      </div>

      <!--No input text, relativo ao código hexadecimal da cor, foi definido autocomplete="iasnsdijsdn" , visto
que autocomplete="off" é ignorado nos browsers mais recentes, quando se pretende desligar o autofill
(uma vez que quando se preenchia o formulario com os dados previamente guardados, a caixa relativa à
cor, era automaticamente preenchida com o email), e desta forma, faz com que essa caixa, não seja 
automaticamente preenchida-->
      <form id="form" autocomplete="off">
        <input type="text" id="name" name="name" placeholder="Inserir Nome"  />
        <input type="tel" id="telephone" name="telephone" placeholder="Inserir Contacto Telefone"
           />
        <input type="email" id="email" name="email" placeholder="Inserir Email"  />
        <input type="website" id="url" name="url" placeholder="Inserir Website"  />
        <input type="website" id="maps" name="maps" placeholder="Inserir Ligação Google Maps"
           />
        <label id="labelcolor" for="favcolor">Definir cor: </label>
        <input type="color" onchange="changeCol()" id="favcolor" name="favcolor" value="#000000"
           />
        <input type="text" autocomplete="iasnsdijsdn" onchange="changeColBox()" id="colorcode" name="colorcode"
          value="#000000"  />
        <label for="image" >Upload Logo (opcional)</label>
        <input type="file" onchange="encodeImageFileAsURL(this)" style="display: none"
          accept="image/jpeg, image/png, image/jpg" id="image" name="image" >
      </form>
      <button id="button"  onclick="generatecode(this.value)">
        Gerar QR code
      </button>

      <div id="qrcodes">
        <div id="qrcode_1" ></div>
        <div id="qrcode_2" ></div>
      </div>


  
      <div id="download" style="display: none;"></div>
      <!-- Div criada para criar o qrcode 1000x1000 que será utilizado no download, não sendo visivel
      na pagina-->
      


      <button disabled id="download_button"  onclick="downloadcode()">
        Descarregar QR code
      </button>

    </div>
  </div>

And this is my old Html

 
      <input type="text" name="name" placeholder="Inserir Nome"  />
      <input type="tel" name="telephone" placeholder="Inserir Contacto Telefone"  />
      <input type="email" name="email" placeholder="Inserir Email"  />
      <input type="website" name="url" placeholder="Inserir Website"  />

      <button  onclick="generatecode()">
        Gerar QR code
      </button>


      <div id="qrcodes">
        <div id="qrcode_1" ></div>
        <div id="qrcode_2" ></div>
      </div>

      <!-- Div criada para criar o qrcode 1000x1000 que será realizado o download, não sendo visivel
      na pagina-->
      <div id="download" style="display: none;"></div>


      <button id="download_button"  onclick="downloadcode()">
        Descarregar QR code
      </button>

    </div>
  </div>

My old wait of generate the qrcode

  new QRCode(document.getElementById("download"),


          {
            text: 'MECARD:'   'N:'   name  
              ';TEL:'   $('input[name="telephone"]').val()  
              ';EMAIL:'   $('input[name="email"]').val()  
              ';URL:'   $('input[name="url"]').val()  
              ';;',
            width: 1000,
            height: 1000,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H

          });

And the download function

/ Função que faz o download do qrcode em jpg
    function downloadcode() {

      var link = document.createElement("a");
      link.download = "qrcode.jpg";



      var teste = document.getElementById("download");


      link.href = teste.querySelector('img').src;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

EDIT 2:

After trying several stuff, if i use

<img src="data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=" id="download" />

instead of

 <div id="download" ></div>

the qrcode i try to generate the Qrcode to the img element, however my img continues blank .

However if i let my «download» stay only as a div, my Qrcore appear in it, as it should be. However after that happen, since it is not a img element, i am having problems in trying to get the URL (if i could get it, i think my problem would be solved)

Thank You again

CodePudding user response:

Solved my problem! Was able to find this tutorial https://www.studentstutorial.com/javascript/convert-html-div-element using html2canvas, was able to turn my Div into a image, and then download it as normal

  • Related