// script.js const searchBtn = document.getElementById("searchBtn"); const queryInput = document.getElementById("query"); const resultsDiv = document.getElementById("results"); // تابع دانلود عکس از URL function downloadImage(url, filename = 'product.jpg') { // اطمینان از اینکه URL معتبر است if (!url || url.startsWith('data:') || url.startsWith('blob:')) { // اگر URL دیتای داخلی است، مستقیم دانلود میشود const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); return; } // برای URLهای خارجی: با fetch دانلود و به عنوان blob دانلود fetch(url) .then(response => { if (!response.ok) throw new Error('Network response was not ok'); return response.blob(); }) .then(blob => { const blobUrl = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = filename; document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(blobUrl); document.body.removeChild(a); }) .catch(err => { console.error('Failed to download image:', err); alert('در حال حاضر امکان دانلود این تصویر وجود ندارد.'); }); } searchBtn.addEventListener("click", async () => { const q = queryInput.value.trim(); if (!q) return alert("لطفاً یک نام محصول وارد کنید"); resultsDiv.innerHTML = "
در حال بارگذاری...
"; try { const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`); const data = await res.json(); const hasResults = data.basalam?.length > 0 || data.torob?.length > 0 || data.digikala?.length > 0; if (!hasResults) { resultsDiv.innerHTML = "هیچ نتیجهای یافت نشد
"; return; } resultsDiv.innerHTML = ""; const allItems = [ ...data.basalam.map(item => ({...item, source: 'باسلام'})), ...data.torob.map(item => ({...item, source: 'ترب'})), ...data.digikala.map(item => ({...item, source: 'دیجیکالا'})) ]; if (allItems.length === 0) { resultsDiv.innerHTML = "هیچ نتیجهای یافت نشد
"; return; } allItems.forEach(item => { const col = document.createElement("div"); col.className = "col"; const card = document.createElement("div"); card.className = "card h-100"; const title = item.title || item.name || "بدون عنوان"; const price = item.price !== undefined && item.price !== null ? (typeof item.price === 'object' ? (item.price.value || JSON.stringify(item.price)) : item.price) : "—"; const image = (item.image || "https://via.placeholder.com/150").trim(); card.innerHTML = `${price}
منبع: ${item.source}خطا در دریافت دادهها
"; } }); // Allow Enter key queryInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { searchBtn.click(); } });