Print from frontend javascript?

2019-02-13 18:04发布

问题:

Is it possible to print something with a printer with javascript in the browser?

I want to print a receipt number, so if it's possible, what is the fastest printer so when the user clicks on a button it will print out eg. "1234" on a small paper.

Thanks

回答1:

You can't access the printer directly from Javascript but you can call window.print() which will initiate the standard browser print behaviour. Using this, you could try two techniques to achieve what you're after:

Just before calling window.print() inject a dynamic print stylesheet that only shows the elements with the text you're wanting to print. You would need to be careful to cleanup any previous print stylesheets. Or in fact you could just use an element <div id="printable"> which is the only visible element in your print stylesheet and insert any text to be printed in that. (Just be mindful if this is a website which users may actually want to print)

It's also possible to call print() directly on an iframe window, which you could populate with your desired text. For example:

var iframe = document.createElement('iframe');

iframe.onload = function() {
    var doc = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
    doc.getElementsByTagName('body')[0].innerHTML = "<p>1234</p>";

    iframe.contentWindow.focus(); // This is key, the iframe must have focus first
    iframe.contentWindow.print();
}

document.getElementsByTagName('body')[0].appendChild(iframe);


回答2:

You can't access print settings from within the browser.

This is due to security considerations, otherwise printers worldwide would be printing non-stop.

The only thing you can do regarding printing in javascript in call window.print();.