Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

803
Visualizações
Delay window.print() until page has loaded within an ajax request to avoid a blank print screen?

What I'm trying to do with this code is make an ajax request to something that generates barcodes and returns them to be printed. When I make the request it generates everything correctly but the print window is blank. If I cancel the print window, the underlying window has the correct barcodes to be printed. I'm suspecting that I need to delay the .print() until the child window has been fully loaded, but the solution is eluding me. Thanks in advance for any help!

var barcode = $.ajax({
     url: "barcode.php",
     method: "POST",
     data: {
            name : name,
            text : text,
            number : numLines
            },
});
var printText;
barcode.done(function( jqXHR, textStatus ) {
    printText = jqXHR;
    var WindowObject = window.open();
    WindowObject.document.writeln(printText);
    WindowObject.focus();
    WindowObject.print();

});

This is all wrapped in a $( document ).ready(function(){});

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

After doing a great bit of research, I found two answers: one that is probably better convention-wise, and one that is easier to implement, but (sadly) also pretty hacky.

For the first solution, it's just simplifying the second solution. Just supply a url to window.open which results in a page that will have the content and a script that calls window.print when everything is loaded. This should be easy as you seem to be hosting the pages here, so you can just make "barcode.php" accept GET parameters and all you need to do is add the print functionality to the page.

// Assumes parameters provided are safe to use in a url.
window.open('barcode.php?name=' + name + '&text=' + text + '&number=' + number');

Then, in the content that's sent back from "barcode.php", add a script:

document.onload = function() {
    window.focus();
    window.print();
    window.close();
};

This is far better than any other solution I can think of, especially because you should (I didn't test this, so I don't really know) be able to use the load event or onload.


I'm only providing the hacky solution for two reasons: I spent a little while on it and it may prove useful one day. I would like to stress, however, that this second solution is pretty silly. I would advise against using it in a production environment and

If you care to use it, here's how it goes:

  • Create a window with window.open
  • write (or writeln) whatever content you want to the new window.
  • write a <script> containing some functionality to the new window:
    • Check if document.readyState is "complete"; if so, do your print procedure. Otherwise:
    • Use setTimeout to recheck document.readyState just like above. (Basically, repeat in some way.)
    • We do this because we can't use the load event or onload because neither fire.

Here's some example code to show that off:

var WindowObject = window.open();
WindowObject.document.write('<img src="http://i.imgur.com/Jvh1OQm.jpg" />'); // This is your content to be printed
WindowObject.document.write('<script>(' + (function() {
    function checkReadyState() {
        if (document.readyState === 'complete') {
            window.focus();
            window.print();
            window.close();
        } else {
            setTimeout(checkReadyState, 200); // May need to change interval
        }
    }

    checkReadyState();
}) + ')();</sc' + 'ript>');

Again, I'm going to stress this is a very bad way of doing what is wanted. I only provide this knowledge because I feel it could possibly be useful to someone.

over 4 years ago · Santiago Trujillo Relatório

0

You could try to use WindowObject.onload = function () { ... }; this way:

barcode.done(function( jqXHR, textStatus ) {
    printText = jqXHR;
    var WindowObject = window.open();
    WindowObject.onload = function () {
        WindowObject.document.writeln(printText);
        WindowObject.focus();
        WindowObject.print();
    };
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda