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