You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript控制打印弹窗?点击确定执行代码,取消则不执行

Solution: Run Code Only When User Clicks "OK" in Print Dialog

Alright, let's solve this problem. The main issue here is that the native window.print() method doesn't directly tell us whether the user clicked "OK" or "Cancel" in the print dialog. But we can use browser media query listeners to reliably distinguish between the two actions and run your code only when the user confirms the print.

Step-by-Step Implementation

Here's a robust solution that uses the matchMedia API to detect when the browser enters/exits print mode (which only happens if the user clicks "OK" in the dialog):

(function() {
  // Flag to track if user confirmed the print
  let printConfirmed = false;
  // Create a media query listener for print mode
  const printMediaQuery = window.matchMedia('print');

  // Listen for changes in print mode
  printMediaQuery.addEventListener('change', function(event) {
    if (event.matches) {
      // Browser entered print mode → user clicked "OK"
      printConfirmed = true;
    } else {
      // Browser exited print mode
      if (printConfirmed) {
        // Run your desired code here (only after confirmed print)
        const xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState === 4 && this.status === 200) {
            console.log('Response', this.responseText);
            // document.getElementById("demo").innerHTML = this.responseText;
          }
        };
        // Replace with your actual endpoint URL
        xhttp.open("POST", "<?php echo site_url('AppsCtr/updatePrintLog'); ?>", true);
        // If your endpoint requires form data, send it here (e.g., xhttp.send(formData))
        xhttp.send();

        // Reset flag for future print attempts
        printConfirmed = false;
      }
    }
  });

  // Function to trigger the print dialog (bind this to your print button)
  window.triggerPrint = function() {
    window.print();
  };
})();

How It Works

  1. Media Query Listener: We use window.matchMedia('print') to listen for when the browser switches to print mode. This only fires if the user clicks "OK" in the print dialog.
  2. Flag Tracking: When print mode is entered, we set printConfirmed to true. If the user clicks "Cancel", this event never triggers, so the flag stays false.
  3. Run Code on Exit: When the browser exits print mode (after printing finishes or the preview is closed), we check if printConfirmed is true—if yes, we execute your AJAX code.

Binding to Your Print Button

Attach the print trigger to your button. For a simple inline approach:

<button onclick="triggerPrint()">Print Document</button>

For cleaner code (avoiding global functions), add this inside your IIFE:

document.getElementById('your-print-button-id').addEventListener('click', window.print);

Notes

  • Browser Compatibility: This works in all modern browsers (Chrome, Firefox, Edge, Safari) that support the matchMedia API's change event.
  • Edge Cases: If the user closes the print preview window without finishing the print, your code will still run—this is usually desired, as the user did confirm the print initially.

内容的提问来源于stack exchange,提问作者Mohammad Shahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:06:20