// Content script for Quality Recticel Print Helper console.log('Quality Recticel Print Helper - Content script loaded'); // Check if we're on the print module page if (window.location.pathname.includes('print_module')) { console.log('Print module page detected, initializing extension features'); // Wait for DOM to be ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initializePrintExtension); } else { initializePrintExtension(); } } function initializePrintExtension() { console.log('Initializing print extension features'); // Add extension status indicator addExtensionStatusIndicator(); // Override the print button functionality overridePrintButton(); // Add printer selection dropdown addPrinterSelection(); // Check extension status checkExtensionStatus(); } function addExtensionStatusIndicator() { // Detect browser type const browserType = getBrowserType(); // Create status indicator element const statusIndicator = document.createElement('div'); statusIndicator.id = 'extension-status'; statusIndicator.style.cssText = ` position: fixed; top: 10px; right: 10px; background: ${browserType === 'chrome' ? '#28a745' : '#ffc107'}; color: ${browserType === 'chrome' ? 'white' : 'black'}; padding: 8px 12px; border-radius: 4px; font-size: 12px; z-index: 9999; box-shadow: 0 2px 4px rgba(0,0,0,0.2); max-width: 250px; `; if (browserType === 'chrome') { statusIndicator.textContent = '🖨️ Print Extension Active (Direct Print Available)'; } else { statusIndicator.innerHTML = `🖨️ Print Extension Active
${browserType.toUpperCase()} - Browser Print Mode`; } document.body.appendChild(statusIndicator); // Hide after 4 seconds (longer for non-Chrome browsers) setTimeout(() => { statusIndicator.style.opacity = '0'; statusIndicator.style.transition = 'opacity 0.5s'; setTimeout(() => statusIndicator.remove(), 500); }, browserType === 'chrome' ? 3000 : 5000); } // Detect browser type function getBrowserType() { const userAgent = navigator.userAgent.toLowerCase(); if (userAgent.includes('edg/')) return 'edge'; if (userAgent.includes('brave')) return 'brave'; if (userAgent.includes('chrome') && !userAgent.includes('edg/')) return 'chrome'; return 'chromium'; } function overridePrintButton() { // Find the print button const printButton = document.getElementById('print-label-btn'); if (printButton) { console.log('Found print button, overriding functionality'); // Remove existing event listeners by cloning the element const newPrintButton = printButton.cloneNode(true); printButton.parentNode.replaceChild(newPrintButton, printButton); // Add new event listener for extension printing newPrintButton.addEventListener('click', handleExtensionPrint); // Update button text based on browser capabilities const browserType = getBrowserType(); if (browserType === 'chrome') { newPrintButton.innerHTML = '🖨️ Print Direct'; newPrintButton.title = 'Print directly to default printer (Chrome Extension)'; } else { newPrintButton.innerHTML = '🖨️ Print Enhanced'; newPrintButton.title = `Enhanced printing for ${browserType.toUpperCase()} browser - Opens optimized print dialog`; } console.log('Print button override complete'); } else { console.log('Print button not found, will retry...'); // Retry after 1 second if button not found yet setTimeout(overridePrintButton, 1000); } } function handleExtensionPrint(event) { event.preventDefault(); event.stopPropagation(); console.log('Extension print button clicked'); // Get the label preview element const labelPreview = document.getElementById('label-preview'); if (!labelPreview) { alert('Label preview not found. Please select an order first.'); return; } // Show printing status showPrintStatus('Preparing to print...', 'info'); // Create complete HTML for printing const printHTML = createPrintableHTML(labelPreview); // Get selected printer from dropdown const selectedPrinterId = window.getSelectedPrinter ? window.getSelectedPrinter() : 'default'; // Try direct printing first, then fallback chrome.runtime.sendMessage({ action: 'print_label', data: { html: printHTML, timestamp: Date.now(), printerId: selectedPrinterId } }, (response) => { if (response && response.success) { handlePrintResponse(response); } else { console.log('Direct printing failed, trying fallback method'); showPrintStatus('Direct printing unavailable, using browser print...', 'info'); // Try fallback method chrome.runtime.sendMessage({ action: 'fallback_print', data: { html: printHTML, timestamp: Date.now(), printerId: selectedPrinterId } }, handlePrintResponse); } }); } function createPrintableHTML(labelElement) { // Get the computed styles and create a complete HTML document const styles = ` `; const bodyContent = ` `; return ` Quality Recticel Label ${styles} ${bodyContent} `; } function handlePrintResponse(response) { console.log('Print response:', response); if (response && response.success) { showPrintStatus('✅ Label sent to printer successfully!', 'success'); // Update the order status in the table if possible updateOrderPrintStatus(); } else { const errorMsg = response?.error || 'Unknown error occurred'; showPrintStatus(`❌ Print failed: ${errorMsg}`, 'error'); // Fallback to browser print dialog setTimeout(() => { if (confirm('Direct printing failed. Open browser print dialog?')) { window.print(); } }, 2000); } } function showPrintStatus(message, type) { // Remove existing status messages const existingStatus = document.getElementById('print-status-message'); if (existingStatus) { existingStatus.remove(); } // Create status message const statusDiv = document.createElement('div'); statusDiv.id = 'print-status-message'; statusDiv.style.cssText = ` position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#17a2b8'}; color: white; padding: 15px 25px; border-radius: 8px; font-size: 14px; z-index: 10000; box-shadow: 0 4px 8px rgba(0,0,0,0.3); text-align: center; min-width: 300px; `; statusDiv.textContent = message; document.body.appendChild(statusDiv); // Auto-remove after 3 seconds for success/info, 5 seconds for errors const timeout = type === 'error' ? 5000 : 3000; setTimeout(() => { statusDiv.style.opacity = '0'; statusDiv.style.transition = 'opacity 0.5s'; setTimeout(() => statusDiv.remove(), 500); }, timeout); } function addPrinterSelection() { // Get available printers and add selection dropdown chrome.runtime.sendMessage({action: 'get_printers'}, (response) => { if (response && response.success && response.printers.length > 0) { console.log('Available printers:', response.printers); // Could add printer selection UI here if needed } }); } function updateOrderPrintStatus() { // Find selected row in table and update print status const selectedRow = document.querySelector('.print-module-table tbody tr.selected'); if (selectedRow) { const printStatusCell = selectedRow.querySelector('td:nth-last-child(2)'); // Second to last column if (printStatusCell) { printStatusCell.innerHTML = '✓ Yes'; } } } function checkExtensionStatus() { // Verify extension is working chrome.runtime.sendMessage({action: 'check_extension'}, (response) => { if (response) { console.log('Extension status:', response); } else { console.error('Extension communication failed'); } }); } // Add CSS for extension-specific styling const extensionStyles = document.createElement('style'); extensionStyles.textContent = ` #print-label-btn { background: linear-gradient(45deg, #28a745, #20c997) !important; border: none !important; transition: all 0.3s ease !important; } #print-label-btn:hover { background: linear-gradient(45deg, #218838, #1ea97c) !important; transform: translateY(-1px) !important; box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important; } `; document.head.appendChild(extensionStyles);