File Manager
Editing: e-commerce.js
// =========================== // 🌟 SEARCH FUNCTIONALITY // =========================== function initializeSearch() { const searchField = document.getElementById("search"); const resultDiv = document.getElementById("result"); function liveSearch() { const query = searchField.value.trim(); if (query.length > 0) { resultDiv.style.display = "block"; const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { resultDiv.innerHTML = xhr.responseText; resultDiv.querySelectorAll("a").forEach((link) => { link.addEventListener("click", () => { const productId = link.getAttribute("data-id"); moveProductToTop(`product-${productId}`); resultDiv.style.display = "none"; searchField.value = ""; }); }); } }; const searchPath = `${window.location.origin}/search.php`; xhr.open("GET", `${searchPath}?query=${encodeURIComponent(query)}`, true); xhr.send(); } else { resultDiv.innerHTML = ""; resultDiv.style.display = "none"; } } searchField.addEventListener("input", liveSearch); document.addEventListener("click", (event) => { if (!resultDiv.contains(event.target) && !searchField.contains(event.target)) { resultDiv.style.display = "none"; resultDiv.innerHTML = ""; searchField.value = ""; } }); } function moveProductToTop(productId) { const productElement = document.getElementById(productId); const productsContainer = document.getElementById("products"); if (productElement && productsContainer) { productsContainer.insertBefore(productElement, productsContainer.firstChild); } } window.addEventListener("load", initializeSearch); // =========================== // 🚀 SERVICE WORKER REGISTRATION // =========================== if ("serviceWorker" in navigator && "PushManager" in window) { navigator.serviceWorker.register("/service-worker.js") .then((registration) => { console.log("✅ Service Worker Registered:", registration); // Show the soft ask after a delay or specific user action setTimeout(() => { showNotificationPrompt(); }, 15000); // Show after 10 seconds }) .catch((err) => console.error("❌ Service Worker Registration Failed:", err)); } // Show the soft ask UI only if not shown before function showNotificationPrompt() { if (!localStorage.getItem("notificationPromptShown")) { const notificationPrompt = document.getElementById("notification-prompt"); if (notificationPrompt) { notificationPrompt.style.display = "block"; } } } // Handle the "Enable Notifications" button click document.getElementById("enable-notifications")?.addEventListener("click", async () => { await requestNotificationPermission(); hideNotificationPrompt(); localStorage.setItem("notificationPromptShown", "true"); }); // Handle the "Not Now" button click document.getElementById("not-now")?.addEventListener("click", () => { hideNotificationPrompt(); localStorage.setItem("notificationPromptShown", "true"); }); // Hide the prompt function hideNotificationPrompt() { const notificationPrompt = document.getElementById("notification-prompt"); if (notificationPrompt) { notificationPrompt.style.display = "none"; } } // Request notification permission function requestNotificationPermission() { Notification.requestPermission().then((permission) => { if (permission === "granted") { console.log("✅ Notification permission granted."); autoSubscribeToPush(); } else { console.warn("❌ Push notifications denied by user."); } }); } // Check if the prompt should be shown showNotificationPrompt(); // Auto-subscribe users to push notifications function autoSubscribeToPush() { navigator.serviceWorker.ready.then((registration) => { registration.pushManager.getSubscription().then((subscription) => { if (subscription) { console.log("🔔 User already subscribed:", subscription); return; } // Subscribe the user registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array('BHik82BfHN14SzCOfrZmCssN0nsFIoOBHi8l2hMBh9QLUTjtMXd87Xxbi2HMadLU-WuR9BvlM4Kd2ifS-5dkDg0') }).then((newSubscription) => { console.log("✅ Auto-subscribed to push notifications:", newSubscription); sendSubscriptionToServer(newSubscription); // Save subscription to server }).catch((err) => console.error("❌ Push Subscription Failed:", err)); }); }); } // Send subscription to server function sendSubscriptionToServer(subscription) { fetch('/save-subscription', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(subscription) }).then(response => { if (!response.ok) { throw new Error('Failed to save subscription.'); } console.log('Subscription saved successfully.'); }).catch(error => { console.error('Error saving subscription:', error); }); } // Convert VAPID key to Uint8Array function urlBase64ToUint8Array(base64String) { const padding = "=".repeat((4 - (base64String.length % 4)) % 4); const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/"); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } // =========================== // 📲 PWA INSTALL PROMPT // =========================== let deferredPrompt; window.addEventListener("beforeinstallprompt", (event) => { event.preventDefault(); deferredPrompt = event; if (!window.matchMedia("(display-mode: standalone)").matches) { const installBtn = document.createElement("button"); installBtn.textContent = "Install EIZON"; installBtn.style = ` position: fixed; bottom: 10px; right: 10px; padding: 12px 20px; background: #40e350; color: white; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; box-shadow: 2px 2px 5px rgba(0,0,0,0.2); `; document.body.appendChild(installBtn); installBtn.addEventListener("click", () => { deferredPrompt.prompt(); deferredPrompt.userChoice.then((choiceResult) => { if (choiceResult.outcome === "accepted") { console.log("✅ User installed the PWA"); } else { console.log("❌ User dismissed the PWA install prompt"); } installBtn.remove(); deferredPrompt = null; }); }); } });
💾 Save
⬅ Back