6

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

2 Answers 2

11

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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();.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.