求可切换指定打印机并打印后恢复默认的HTML文档脚本
Hey there! I’ve dealt with exactly this kind of printer-switching frustration before, so I know how stuck you must feel. Let’s walk through a practical solution using JavaScript—this will let you target a specific printer, print your QR code template, and then switch back to the default printer automatically.
Key Notes Up Front
First, a quick heads-up: modern browsers (Chrome, Edge, Firefox) support extensions to the window.print() API for printer management, but this requires user permission (the browser will prompt the first time). Also, this won’t work in older browsers like IE, but assuming you’re using a modern stack, we’re good to go.
Step 1: Get Available Printers & Save Default
First, we’ll fetch the list of printers and store the default one so we can revert later. Here’s a snippet to do that:
async function getPrinterInfo() { try { // Request permission to access printers const permission = await navigator.permissions.query({ name: 'printers' }); if (permission.state !== 'granted') { alert("Please allow printer access to proceed!"); return; } // Get all available printers const printers = await window.queryPrinters(); // Find the default printer const defaultPrinter = printers.find(printer => printer.isDefault); return { printers, defaultPrinter }; } catch (err) { console.error("Error accessing printers:", err); alert("Could not access printer list—check browser compatibility."); } }
Step 2: Print to Target Printer & Revert
Next, we’ll create a function that takes your target printer name, switches to it, prints your HTML content, and then switches back to the default. You can either let the user select a printer from the list, or hardcode the printer name if you know it exactly (just make sure the name matches what the browser returns).
async function printToSpecificPrinter(targetPrinterName) { const { printers, defaultPrinter } = await getPrinterInfo(); if (!printers || !defaultPrinter) return; // Find the target printer const targetPrinter = printers.find(printer => printer.name === targetPrinterName); if (!targetPrinter) { alert(`Printer "${targetPrinterName}" not found!`); return; } try { // Set the target printer as active await window.printer.setPrinter(targetPrinter); // Trigger print for your HTML template (replace with your selector) const printWindow = window.open('', '_blank'); printWindow.document.write(document.getElementById('qr-template').innerHTML); printWindow.document.close(); printWindow.print(); // Wait a bit for print to start, then revert to default setTimeout(async () => { await window.printer.setPrinter(defaultPrinter); printWindow.close(); console.log("Reverted to default printer!"); }, 2000); // Adjust timeout if needed—depends on print job speed } catch (err) { console.error("Print error:", err); // Revert to default even if print fails await window.printer.setPrinter(defaultPrinter); } }
Step 3: Trigger the Print Function
You can call this function from a button click, like so:
<!-- Your QR code template --> <div id="qr-template" style="display:none;"> <!-- Your HTML with QR code here --> <h1>QR Code Document</h1> <img src="your-qr-code.png" alt="QR Code"> </div> <!-- Print button --> <button onclick="printToSpecificPrinter('My Non-Default Printer')">Print to Target Printer</button>
Pro Tips & Edge Cases
- Printer Name Matching: Printer names are case-sensitive and must exactly match what the browser returns. If you’re unsure, add a dropdown to let users select from the fetched printer list instead of hardcoding.
- Browser Support: This works in Chrome 86+, Edge 86+, and Firefox 106+. Test in your target browser first.
- Permission Handling: If the user denies printer access, the function will alert them—make sure to handle this gracefully.
- Timeout Adjustment: The 2-second timeout might need tweaking depending on how fast your print job spools. If the default printer reverts too early, increase the timeout.
内容的提问来源于stack exchange,提问作者Robin

