0

I want to open a new tab in javascript with print window already opened.I have tried the following code but it is not working

function OpenInNewTab() {
        var win = window.open('http://stackoverflow.com/questions/6808650/triggering-ctrl-s-or-ctrl-p-via-a-button', '_blank');
        console.log(win);
        win.focus();
        win.onload = function() {
            win.print();
        };
    }

How can I achieve the same thing

Edit 1:

I have tried like this also but does not working

function OpenInNewTab() {
        var win = window.open('http://stackoverflow.com/questions/6808650/triggering-ctrl-s-or-ctrl-p-via-a-button', '_blank');
        win.document.attachEvent("load", function() {
            window.print();
            alert("called")
        })

    } 
gaurav
  • 128
  • 1
  • 8

2 Answers2

1

I found the problem why in chrome not working. Please refer the following code :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="age_validation_input"> <button type="button" id="age_validation_btn" onclick="OpenInNewTab()"> Test </button>

<script type="text/javascript">
function OpenInNewTab() {
        var win = window.open('https://stackoverflow.com/questions/6808650/triggering-ctrl-s-or-ctrl-p-via-a-button', '_blank','height=600,width=800');
        console.log(win);
        win.focus();
        //win.onload = function() {
        //  alert("Hello");
        //    print();
        //};
        //win.onload = "alert('hello');"

        setTimeout(function(){win.print();win.close();}, 3000);
    }

</script>

When you run above code it shows the following error :

enter image description here

so, to resolve this please refer How do I get around window.opener cross-domain security

Hope this will helps :)

Community
  • 1
  • 1
Hardipsinh Jadeja
  • 1,180
  • 1
  • 13
  • 30
0

So basically what you want to do, or rather, what you can do is to make the page you want to print. Open that page in a new tab. Then in bottom of the body of the page you want to print, add this:

 <script>         
   var yourName= "whateverYouWannaNameTheDocument";
            document.title = yourName;
            window.print();
</script>

This worked for me while generating invoices.