0

I'm trying to popup the browser print option for an external URL without opening it in a new tab.

 <a href="##" onclick="printBGReport();" align="center">Print Report</a> <br/>
  <script>
    function printBGReport(){
        var W = window.open(document.getElementById('reportBGID').src);
        W.window.print();            
    }
  </script>

This code is working fine; however, it opens a new tab with the print option. Also, if I use chrome my current tab dies after opening the new one.

Max Boy
  • 317
  • 6
  • 21
  • When I try to print an iFrame content, I got the error: Permission denied to access property "print" on cross-origin object – Max Boy Sep 25 '18 at 15:50
  • You can't access a third-party page due to the [Same-origin policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy). – Teemu Sep 25 '18 at 16:53

1 Answers1

0

You can use a 0x0 iframe to do this. Something like (untested):

<script>
var iframe = document.getElementById("my-iframe");

iframe.contentWindow.innerHTML = "<strong>hello world</strong>";

iframe.print();

</script>

<style>
#my-iframe {
    width: 0;
    height: 0;
}
</style>
oooyaya
  • 1,773
  • 1
  • 15
  • 39
  • I got an error: iframe.print is not a function – Max Boy Sep 25 '18 at 15:48
  • Like I said, not tested. It may be `iframe.contentWindow.print();` – oooyaya Sep 25 '18 at 15:53
  • When I try to print an iFrame content, I got the error: Permission denied to access property "print" on cross-origin object – Max Boy Sep 25 '18 at 15:53
  • If your iframe source is on a different domain (which that error suggests is the case), the solution I provided wont work. That's why what I provided uses `.innerHTML` instead of `.src`. You can do some trickery like `GET`ing the page source but at that point, just add a `.close()` after `.print()` to what you originally had. It'll still open a tab, but it'll close it immediately after printing. – oooyaya Sep 25 '18 at 15:55
  • I followed your example with innerHTML and it says: TypeError: iframe is null – Max Boy Sep 25 '18 at 15:59