Skip to content

qz-tray.js:768 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') QZ Tray version: 2.2.4 and Vue js #1323

Duplicate of#1319
@robertoedu

Description

@robertoedu

I am trying to print PDF files that I receive via URL, but I am encountering an error.

qz-tray.js:768 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0')
at Object.versionCompare (qz-tray.js:768:1)
at Object.data (qz-tray.js:863:1)
at Object.print (qz-tray.js:1645:1)
at reader.onloadend (EtiquetasIntelipostPage.vue:339:1)

Whenever it reaches the print part, this error occurs.

Here is how I connect to the WebSocket and sign the requests:

<q-btn
unelevated
color="primary"
:disable="!selectedDevice"
label="Imprimir"
class="q-ml-xl flex flex-rigth"
@click="getNotafiscal(filtros)"
/>

const getNotafiscal = (filtros = {}) => {
notafiscalService.getIntelipost(filtros).then((response) => {
if (response.status === 200) {
playSound('success')
printLabel(response.data.data.content.label_url)
}
}).catch(errors => {
$q.notify({
color: 'warning',
message: GetErrorMessage(errors)
})
})
}
const printLabel = async (url) => {
console.log('URL do PDF:', url)

  try {
    if (!isQZConnected.value) {
      await connectQZTray()
    }

    const response = await fetch(url)
    if (!response.ok) throw new Error('Erro ao baixar etiqueta')

    const blob = await response.blob()
    console.log('Blob do arquivo:', blob)

    const reader = new FileReader()

    reader.onloadend = async () => {
      if (!reader.result) {
        console.error('Erro: O FileReader não conseguiu ler o arquivo.')
        return
      }

      const base64Data = reader.result.split(',')[1]
      console.log('Tamanho do Base64:', base64Data.length)

      if (!base64Data || base64Data.length < 1000) {
        console.error('Erro: Base64 gerado é muito pequeno, pode estar corrompido.')
        return
      }

      if (!selectedDevice.value) {
        console.error('Nenhuma impressora foi selecionada!')
        return
      }

      const version = await qz.api.getVersion()
      console.log('QZ Tray versão:', version)

      // 🔹 Configuração de impressão
      const config = qz.configs.create(selectedDevice.value, {
        margins: 0,
        scaleContent: false,
        orientation: 'portrait'
      })

      // 🔹 Opções testadas
      const data = [{
        type: 'pixel',
        format: 'pdf',
        flavor: 'base64',
        data: base64Data
      }]

      console.log('Enviando para a impressora...')
      console.log('QZ Tray está ativo?', qz.websocket.isActive())
      await qz.print(config, data)
        .then(() => console.log('Etiqueta enviada para a impressora!'))
        .catch(error => console.error('Erro ao imprimir etiqueta:', error))
    }

    reader.readAsDataURL(blob) // Converte para Base64
  } catch (error) {
    console.error('Erro ao imprimir etiqueta:', error)
  }
}

Activity

changed the title qz-tray.js:768 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') qz-tray.js:768 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') QZ Tray version: 2.2.4 and Vue js on Mar 13, 2025
tresf

tresf commented on Mar 13, 2025

@tresf
Contributor

Can you try to use the qz-tray.js version from our master branch and see if it goes away?

robertoedu

robertoedu commented on Mar 13, 2025

@robertoedu
Author

Just copy and paste the qz-tray-js in node-modules?

tresf

tresf commented on Mar 13, 2025

@tresf
Contributor

Just copy and paste the qz-tray-js in node-modules?

Yes... I think this is a duplicate of #1320 #1301

robertoedu

robertoedu commented on Mar 13, 2025

@robertoedu
Author

Just copy and paste the qz-tray-js in node-modules?

Yes... I think this is a duplicate of #1320 #1301

Well, that message is gone, but now my setCertificatePromise and setSignaturePromise are not working.

robertoedu

robertoedu commented on Mar 13, 2025

@robertoedu
Author

I am fetching the certificate and trying to connect to the WebSocket, but after connecting, when I try to sign it as described in the documentation, the signing process does not occur, and an error is returned.

const connectQZTray = async () => {
      try {
        if (!qz.websocket.isActive()) {
          console.log('Conectando ao QZ Tray...')
          qz.security.setCertificatePromise(() => {
            return fetch(window.location.origin + '/digital-certificate.txt', {
              cache: 'no-store',
              headers: { 'Content-Type': 'text/plain' }
            })
              .then(response => {
                if (!response.ok) {
                  return response.text().then(text => Promise.reject(new Error(`Erro ao carregar certificado: ${text}`)))
                }
                return response.text()
              })
              .then(certText => {
                isCertificateLoaded.value = true
                return certText
              })
              .catch(error => {
                return Promise.reject(error)
              })
          })
          await qz.websocket.connect({ retries: 5, delay: 2 }).then(() => {
            qz.security.setSignatureAlgorithm('SHA512')
            qz.security.setSignaturePromise((toSign) => {
              console.log('Solicitando assinatura para:', toSign)
              return fetch('http://localhost:8080/qzsignature?request=TESTE')
                .then(response => {
                  if (!response.ok) {
                    return response.text().then(text => Promise.reject(new Error(`Erro na assinatura: ${text}`)))
                  }
                  return response.text()
                })
                .then(signature => {
                  console.log('Assinatura recebida:', signature)
                  return signature
                })
                .catch(error => {
                  console.error('Erro ao assinar requisição:', error)
                  throw error
                })
            })
            console.log('Conectado ao QZ Tray.')
            // 5 tentativas com delay de 2s
            console.log('QZ Tray conectado!')
            isQZConnected.value = true // Marca que o QZ Tray está conectado
          })
        }
      } catch (error) {
        console.error('Erro ao conectar ao QZ Tray:', error)
      }
    }
const printLabel = async (url) => {
      console.log('URL do PDF:', url)

      try {
        if (!isQZConnected.value) {
          await connectQZTray()
        }

        const response = await fetch(url)
        if (!response.ok) throw new Error('Erro ao baixar etiqueta')

        const blob = await response.blob()
        console.log('Blob do arquivo:', blob)

        const reader = new FileReader()

        reader.onloadend = async () => {
          if (!reader.result) {
            console.error('Erro: O FileReader não conseguiu ler o arquivo.')
            return
          }

          const base64Data = reader.result.split(',')[1]
          console.log('Tamanho do Base64:', base64Data.length)

          if (!base64Data || base64Data.length < 1000) {
            console.error('Erro: Base64 gerado é muito pequeno, pode estar corrompido.')
            return
          }

          if (!selectedDevice.value) {
            console.error('Nenhuma impressora foi selecionada!')
            return
          }

          const version = await qz.api.getVersion()
          console.log('QZ Tray versão:', version)

          // 🔹 Configuração de impressão
          const config = qz.configs.create(selectedDevice.value, {
            margins: 0,
            scaleContent: false,
            orientation: 'portrait'
          })

          // 🔹 Opções testadas
          const data = [{
            type: 'pixel',
            format: 'pdf',
            flavor: 'base64',
            data: base64Data
          }]

          console.log('Enviando para a impressora...')
          console.log('QZ Tray está ativo?', qz.websocket.isActive())
          await qz.print(config, data)
            .then(() => console.log('Etiqueta enviada para a impressora!'))
            .catch(error => console.error('Erro ao imprimir etiqueta:', error))
        }

        reader.readAsDataURL(blob) // Converte para Base64
      } catch (error) {
        console.error('Erro ao imprimir etiqueta:', error)
      }
    }

qz-tray.js:768
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0')
at Object.versionCompare (qz-tray.js:768:1)
at Object.data (qz-tray.js:863:1)
at Object.print (qz-tray.js:1646:1)
at reader.onloadend (EtiquetasIntelipostPage.vue:338:1)

tresf

tresf commented on Mar 13, 2025

@tresf
Contributor

It is expected that setCertificatePromise and setSignaturePromise are passed a promise-style function (resolve, reject) => however your function never calls resolve() or reject().

This code is untested, but these are the mistakes that I have found...

-          qz.security.setCertificatePromise(() => {
+          qz.security.setCertificatePromise((resolve, reject) => {
            return fetch(window.location.origin + '/digital-certificate.txt', {
              cache: 'no-store',
              headers: { 'Content-Type': 'text/plain' }
            })
              .then(response => {
                if (!response.ok) {
-                 return response.text().then(text => Promise.reject(new Error(`Erro ao carregar certificado`)))
+                 reject(`Erro ao carregar certificado: ${text}`)
                }
+               else {
                return response.text()
+               }
              })
              .then(certText => {
                isCertificateLoaded.value = true
-               return certText
+               resolve(certText)
              })
              .catch(error => {
-               return Promise.reject(error)
+               console.error('Error ...', error)
+               reject(error)
              })
          })
            qz.security.setSignaturePromise((toSign) => {
+            return (resolve, reject) => {
              console.log('Solicitando assinatura para:', toSign)
              return fetch('http://localhost:8080/qzsignature?request=TESTE')
                .then(response => {
                  if (!response.ok) {
                    reject(`Erro na assinatura`)
                  }
+                 else {
                return response.text()
+                 }
                })
                .then(signature => {
                  console.log('Assinatura recebida:', signature)
-                 return signature
+                 resolve(signature)
                })
                .catch(error => {
                  console.error('Erro ao assinar requisição:', error)
-                 throw error
+                 reject(error)
                })
+             }
            })
tresf

tresf commented on Mar 18, 2025

@tresf
Contributor

Closing to due lack of response. Please reopen if you believe this was closed in error.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      qz-tray.js:768 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0') QZ Tray version: 2.2.4 and Vue js · Issue #1323 · qzind/tray