Mohammed Sinan
Mohammed Sinan

Reputation: 11

Close the window when Chrome print dialog is clicked

I want to close the current tab in Chrome when the print button in Print Dialog is clicked by the user. I tried with window.print() and setTimeout(), but this will close the dialog even if the print is canceled by the CANCEL button. Is there is any solution for this?

This is what I have done so far:

function printThis(){
    window.print();
    setTimeout(function(){
        window.close();
    },5000);
}

Upvotes: 1

Views: 3014

Answers (4)

Alo
Alo

Reputation: 976

Very simple! on print page (In my case it is "print-page.html") use this script -

<script>
window.onafterprint = function(){
window.close()
}
</script>

It will close the new tab when the user clicked the print/cancel button! Tested on chrome and works fine.

Make sure you have already called the print interface using this method -

<input type="button" value="button name" onclick="window.open('print-page.html','popUpWindow','height=687,width=1057,left=10,top=10,scrollbars=yes,menubar=no'); return false;" />

Best of luck!

Upvotes: 0

user10845517
user10845517

Reputation:

You can use onafterprint event:

window.onafterprint = function(){ window.close() }

Upvotes: 1

Julian
Julian

Reputation: 1612

please use this code.

window.addEventListener("beforeprint", function(event) { ... });
//or
window.onbeforeprint = function(event) { ... };

window.onbeforeprint will be called when press Ctrl+p or else for opening print dialog

e.g

window.addEventListener("beforeprint", 
                        function(event) {
                            window.close();
                        });

or if you want to close window after print button pressed, please use window.onafterprint like this

window.onafterprint = function(){
   window.close()
}

Upvotes: 1

Googlian
Googlian

Reputation: 6723

You can call the this method in onload, once this print dialog is dismissed the alert prompt will automatically be called and ask the user whether print or not if print has been done, the user will be automatically redirected to the page.

If you want to close the window you should open the particular window by window.open method, you cannot close the window by just opening by URL or redirects.

Example:

window.open("https://yourside.com", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");

Then you can call window.close in the window which is opened by window.open.

window.onload = function () {
    window.print();
    setTimeout(function(){ if(confirm("Have you printed ?")) { window.location.href="/your_page"; } }, 1);
}

Upvotes: 1

Related Questions