Make sure to shut the window once the Chrome print dialog is activated

I'm looking for a way to automatically close the current tab in Chrome when the user clicks on the print button in the Print Dialog. I've tried using window.print() and setTimeout(), but this approach closes the dialog even if the print is canceled by clicking on the CANCEL button. Is there a different solution that might work better?

Here's what I've attempted so far:

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

Answer №1

After the print dialog is dismissed, an alert prompt will ask the user if they want to print or not. If the user chooses to print, they will be redirected back to the page automatically.

To close a window opened using the window.open method, you cannot simply open it by URL or redirects.

For example:

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

You can then use the window.close method on the window opened with window.open.

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

Answer №2

Feel free to utilize this piece of code.

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

window.onbeforeprint gets triggered when the user presses Ctrl+p or any other key combination to open the print dialog

For example:

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

If you wish to automatically close the window after pressing the print button, use window.onafterprint like so

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

Answer №3

To close a window after printing, simply utilize the onafterprint event:

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

Answer №4

Extremely straightforward! To automatically close the print page (in this case called "print-page.html"), you can utilize this script:

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

This will effectively close the new tab when the user clicks the print/cancel button. It has been tested on Chrome and functions perfectly.

Just ensure that you have already initiated the print interface using this approach:

<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;" />

Wishing you all the best!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for sorting data by date in Angular 4

Seeking guidance on how to filter records in a table based on the date column. The current filtering code is generating an error message: ERROR TypeError: Cannot read property 'indexOf' of null temp = [{ "firstName":"Ravi", "date":"2019-04-0 ...

Patience is key when waiting for the completion of a subscription in Angular 8

In my component, I have set up a subscription inside an interval in the onInit method: ngOnInit() { interval(5000).pipe( takeWhile(() => this.isAlive)) .subscribe(() => { this.initialization(); }); } initi ...

What is the correct way to implement useEffect for an asynchronous fetch request in React? Is there a specific method to avoid react-hooks/exhaustive

Hey there, I'm currently encountering an issue with the useEffect hook in React. While the code below is functioning correctly, es-lint keeps suggesting that I include dependencies in the dependency array for useEffect. Code that's working with / ...

Validation of dynamically generated name fields using radio button group

CODE: html <form id="myform" type="post"> <fieldset id="myid1"> <input id="entries_8490_burn_id_1" name="entries[8490][burn_id]" value="1" type="radio"/> <input id="entries_8490_burn_id_2" name="entries[8490][burn ...

Tabulator - Using AJAX to retrieve a JSON document

I am currently working on importing a json file from an Azure blob container using Azure Data Factory. Despite closely following the documentation and researching various resources on Stack Overflow, I am facing challenges with making the ajax request fun ...

Using Vue JS to extract and merge data from an API response in JSON format

Hey there! I'm a new developer working with Vue JS. I have a response body where I need to sum the amount values that have is_paid:true using only the paid_amount. Can someone guide me on how to achieve this in Vue JS? Edit: For example, I want to ad ...

Can you please tell me the name of the ??= operator in Typescript?

The Lit Element repository contains a function called range that utilizes the ??= operator. This operator resembles the nullish coalescing operator but with an equal sign. Do you know what this specific operator is called? Below is the complete code snipp ...

Can't access innerText in Firefox

This is the code snippet I'm having trouble with: <div id="code">My program<br />It is here!</div> <script type="text/javascript"> var program=document.getElementById('code'); ShowLMCButton(program.innerText); </s ...

Establishing communication between a pair of renderer processes within an Electron environment

I am currently developing a program using Electron. The main process (main.js) creates an index window which displays a list of files, specifically images. My goal is to allow users to click on a file from the list and open a second window that shows the s ...

Audio Playlists and Dynamic Loading with WordPress Shortcode

I'm looking to incorporate the wp_audio_shortcode() function using AJAX, and then customize the style of the audio player. However, I'm facing an issue where the HTML code returned by the AJAX request does not allow me to customize the audio play ...

When Sequelize is utilized with the include option, it is encountering issues by returning null values

When performing a model query with includes and there are no matching rows, the result returned includes null values. I have come across this issue multiple times before, but I have yet to find a definitive solution. Model.findOne({ where: { id: 1 }, ...

Updating radio button based on selection change in jQuery

I'm struggling with jQuery and can't seem to figure out how to change the selected radio button based on a value in another select box. <div class="radio-inline" id="sourceDiv" role="group"> <input type="radio" id="sourceBtns1" na ...

Issue: Incomplete data retrieval using JS/React fetchDescription: I am facing

I am currently working on an app centered around the card game Magic. The concept involves pasting a list of cards into a textbox and then clicking a button to display corresponding card images. My approach entails using fetch requests to interact with an ...

How can I create an HTML link that opens a drop-down menu with form functionality?

Feeling a bit perplexed here as I'm not entirely sure how to label this issue... If you're familiar with the Facebook interface, I'm trying to develop a feature similar to the "DOWNWARD ARROW" icon found next to the "comments" or "status" b ...

When using AngularJS in conjunction with Kendo UI, an error may be encountered: "TypeError: Object [object Object] does not possess the method 'each'."

I recently integrated Kendo into my AngularJS project by following a helpful tutorial available at this link. Initially, I didn't encounter any errors in the console when my HTML did not contain any Kendo elements. However, as soon as I implemented t ...

What could be causing worker threads to fail when instantiating a class from a separate file?

The following TypeScript file is being used: import { Worker, WorkerOptions, isMainThread, parentPort } from "worker_threads"; import path from "path"; export class SimpleWorker { private worker: any; constructor() { i ...

jQuery's callback handling often reverses the statement I just made

My current project involves using AJAX with jQuery to send a get request. Once the request is successful, I insert the response into a specific div: $.get("content.php", function(result) { $('#content').html(result); The content I'm fetc ...

Error: Custom Service is behaving unpredictably

My latest project involves creating a customized service. While the service function is returning data as expected, I encounter an issue when calling it in the controller - it returns 'undefined'. Service: var toDoListServices = angular.module( ...

Creating a Jasmine test for the event.target.click can be accomplished by defining a spec that

I need help creating a Jasmine test spec for the following method in my component. Here is my Component Method methodName(event): void { event.preventDefault(); event.target.click(); } I have started writing a test but don't fully cover event. ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...