I am trying to print an external source by clicking on a button. I found multiple scripts on the internet but none of them are working.
So my question is, how can I print a specific page by clicking on a button?
Now I have:
JavaScript
x
<iframe id="frame" src="./test.php"></iframe>
<button onclick="printOtherPage()">Print</button>
<script type="text/javascript">
function printOtherPage() {
document.getElementById('frame').contentWindow.window.print();
</script>
Advertisement
Answer
To do this:
- Create a new iframe element.
- Set the src of the iframe to the page you want to print.
- In javascript,
contentWindow
is used to retrieve the document in iframe.
So use this code to print:
JavaScript
document.getElementById('frame').contentWindow.window.print();
Correct me if I am wrong.