如何用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
- 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. - Flag Tracking: When print mode is entered, we set
printConfirmedtotrue. If the user clicks "Cancel", this event never triggers, so the flag staysfalse. - Run Code on Exit: When the browser exits print mode (after printing finishes or the preview is closed), we check if
printConfirmedistrue—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
matchMediaAPI'schangeevent. - 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
相关产品推荐
相关产品推荐

