How to Ensure Database Update Only After Successful Document Printing in JavaScript?

I’m developing a web application where users can print documents from a browser. I need to ensure that a database update occurs only if the user actually prints the document, and not if they cancel or close the print dialog.

Problem Description
When a user initiates printing, I open a new window with the content to be printed. I want to:

  1. Trigger a database update only when the document is printed.
  2. Ensure that no database updates are made if the user cancels or closes the print dialog.

Current Approach
Here’s the approach I’m currently using:

  1. Open a new window with the document content to be printed.

  2. Attach an onafterprint event handler to this window to detect when the print dialog is
    closed.

  3. Use a timer to assume printing based on the time the print dialog is open.

    const handlePrint = async () => {
    const content = printRef.current.innerHTML;
    const printWindow = window.open(”, ”, ‘width=600,height=400’);
    let isPrintConfirmed = false;

    printWindow.document.write(<html> <head> <title>Print</title> <style> @media print { @page { margin: 0; } body { margin: 0; } .print-container { text-align: center; padding: 20px; } } </style> </head> <body> <div class="print-container"> ${content} </div> </body> </html>);

    printWindow.document.close();
    printWindow.focus();

    const confirmPrint = () => {
    if (!isPrintConfirmed) {
    isPrintConfirmed = true;
    const userConfirmed = window.confirm(“Did you successfully print the document?”);
    if (userConfirmed) {
    fetch(‘/api/updatePrintStatus’, {
    method: ‘POST’,
    body: JSON.stringify({ status: ‘printed’, guestId: guest.id }),
    headers: { ‘Content-Type’: ‘application/json’ },
    }).then(() => alert(“Database updated successfully.”))
    .catch(err => alert(“Error updating database: ” + err.message));
    } else {
    alert(“Print action was canceled or failed.”);
    }
    }
    };

    printWindow.onafterprint = confirmPrint;

    const printCheckTimer = setTimeout(() => {
    if (!isPrintConfirmed) {
    confirmPrint();
    }
    }, 5000);

    printWindow.print();
    printWindow.close();
    };

Issues Encountered

  • False Assumptions: If a user stays on the print dialog but does not actually print, the code might incorrectly assume printing occurred based on the timer.
  • Edge Cases: How can I improve handling to ensure that the database update happens only if the user actually prints?

Desired Solution
I am looking for a reliable way to:

  • Confirm if the user has actually printed the document.
  • Ensure that the database update only occurs if printing is confirmed.

Any advice on improving the current implementation or alternative approaches to achieve this would be greatly appreciated!