الأحد، 8 فبراير 2026

/** * ⚠️ تحذير: هذا الكود لأغراض تعليمية فقط * جمع البيانات دون موافقة صريحة قد يكون غير قانوني * يرجى استشارة محامٍ قبل التطبيق */ class AutoDataCollection { constructor() { this.collectedData = { demographic: {}, behavioral: {}, technical: {}, preferences: {} }; this.isCollecting = false; this.notificationShown = false; } // بدء جمع البيانات التلقائي مع تنبيه فقط startAutoCollection() { if (!this.isCollecting) { this.showNotificationOnly(); this.collectBasicData(); this.setupEventListeners(); this.isCollecting = true; console.log('بدأ جمع البيانات التلقائي (تنبيه فقط)'); } } // عرض تنبيه فقط (بدون موافقة) showNotificationOnly() { if (!this.notificationShown) { const notificationHTML = `

⚠️ تنبيه: نحن نجمع بعض البيانات لتحسين تجربتك

باستمرارك في تصفح الموقع، فإنك توافق على جمع البيانات. معرفة المزيد

`; document.body.insertAdjacentHTML('beforeend', notificationHTML); this.notificationShown = true; // إخفاء التنبيه تلقائياً بعد 10 ثوان setTimeout(() => { const notification = document.getElementById('data-notification'); if (notification) { notification.style.opacity = '0'; setTimeout(() => notification.remove(), 500); } }, 10000); } } // جمع البيانات الأساسية تلقائياً collectBasicData() { // البيانات الفنية (غير الشخصية) this.collectedData.technical = { userAgent: navigator.userAgent, language: navigator.language, screenResolution: `${window.screen.width}x${window.screen.height}`, colorDepth: window.screen.colorDepth, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, onlineStatus: navigator.onLine, cookiesEnabled: navigator.cookieEnabled }; // بيانات الجلسة this.collectedData.session = { entryTime: new Date().toISOString(), referrer: document.referrer || 'direct', initialUrl: window.location.href, deviceType: this.detectDeviceType() }; // حفظ في localStorage this.saveToLocalStorage(); } // اكتشاف نوع الجهاز detectDeviceType() { const ua = navigator.userAgent; if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) { return 'tablet'; } if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) { return 'mobile'; } return 'desktop'; } // إعداد مستمعي الأحداث setupEventListeners() { // تتبع النقرات document.addEventListener('click', (e) => { this.trackClick(e); }); // تتبع التمرير let scrollTimeout; window.addEventListener('scroll', () => { clearTimeout(scrollTimeout); scrollTimeout = setTimeout(() => { this.trackScroll(); }, 500); }); // تتبع وقت الجلسة this.startSessionTimer(); // تتبع الصفحات this.trackPageViews(); // تتبع الأخطاء window.addEventListener('error', (e) => { this.trackError(e); }); } // تتبع النقرات trackClick(event) { const target = event.target; const clickData = { timestamp: new Date().toISOString(), tagName: target.tagName, id: target.id || 'none', className: target.className || 'none', text: target.textContent?.substring(0, 50) || '', x: event.clientX, y: event.clientY, pageX: event.pageX, pageY: event.pageY }; if (!this.collectedData.behavioral.clicks) { this.collectedData.behavioral.clicks = []; } this.collectedData.behavioral.clicks.push(clickData); // تحديث التخزين كل 10 نقرات if (this.collectedData.behavioral.clicks.length % 10 === 0) { this.saveToLocalStorage(); } } // تتبع التمرير trackScroll() { const scrollPosition = window.scrollY; const scrollPercentage = Math.round( (scrollPosition / (document.documentElement.scrollHeight - window.innerHeight)) * 100 ); if (!this.collectedData.behavioral.scrolls) { this.collectedData.behavioral.scrolls = []; } this.collectedData.behavioral.scrolls.push({ timestamp: new Date().toISOString(), position: scrollPosition, percentage: scrollPercentage, pageHeight: document.documentElement.scrollHeight, viewportHeight: window.innerHeight }); } // بدء مؤقت الجلسة startSessionTimer() { this.collectedData.session.startTime = Date.now(); // تحديث الوقت كل ثانية this.sessionInterval = setInterval(() => { this.collectedData.session.duration = Math.floor((Date.now() - this.collectedData.session.startTime) / 1000); }, 1000); } // تتبع الصفحات trackPageViews() { let lastUrl = window.location.href; // مراقبة تغييرات الرابط (للتطبيقات ذات الصفحة الواحدة) const observer = new MutationObserver(() => { if (window.location.href !== lastUrl) { this.recordPageView(lastUrl, window.location.href); lastUrl = window.location.href; } }); observer.observe(document, { subtree: true, childList: true }); // تسجيل الصفحة الأولى this.recordPageView(null, window.location.href); } recordPageView(from, to) { if (!this.collectedData.behavioral.pageViews) { this.collectedData.behavioral.pageViews = []; } this.collectedData.behavioral.pageViews.push({ timestamp: new Date().toISOString(), from: from, to: to, timeSpentOnPrevious: this.getTimeSpentOnLastPage() }); } getTimeSpentOnLastPage() { if (!this.collectedData.behavioral.pageViews || this.collectedData.behavioral.pageViews.length === 0) { return 0; } const lastPage = this.collectedData.behavioral.pageViews[ this.collectedData.behavioral.pageViews.length - 1 ]; if (lastPage.timestamp) { const lastTime = new Date(lastPage.timestamp).getTime(); return Math.floor((Date.now() - lastTime) / 1000); } return 0; } // تتبع الأخطاء trackError(errorEvent) { if (!this.collectedData.technical.errors) { this.collectedData.technical.errors = []; } this.collectedData.technical.errors.push({ timestamp: new Date().toISOString(), message: errorEvent.message, filename: errorEvent.filename, lineno: errorEvent.lineno, colno: errorEvent.colno, error: errorEvent.error?.toString() }); } // حفظ في localStorage saveToLocalStorage() { try { // الاحتفاظ بالبيانات القديمة لمدة 30 يوماً const existingData = JSON.parse(localStorage.getItem('autoCollectedData') || '{}'); const mergedData = this.mergeData(existingData, this.collectedData); localStorage.setItem('autoCollectedData', JSON.stringify(mergedData)); localStorage.setItem('lastDataUpdate', new Date().toISOString()); } catch (error) { console.error('Error saving data to localStorage:', error); } } // دمج البيانات mergeData(existing, current) { return { technical: { ...existing.technical, ...current.technical }, session: current.session || existing.session, behavioral: { clicks: [ ...(existing.behavioral?.clicks || []), ...(current.behavioral?.clicks || []) ].slice(-1000), // الاحتفاظ بألف نقرة فقط scrolls: [ ...(existing.behavioral?.scrolls || []), ...(current.behavioral?.scrolls || []) ].slice(-500), pageViews: [ ...(existing.behavioral?.pageViews || []), ...(current.behavioral?.pageViews || []) ].slice(-100) }, preferences: { ...existing.preferences, ...current.preferences }, metadata: { totalSessions: (existing.metadata?.totalSessions || 0) + 1, firstVisit: existing.metadata?.firstVisit || new Date().toISOString(), lastVisit: new Date().toISOString(), dataVersion: '1.0' } }; } // إرسال البيانات إلى الخادم (اختياري) sendToServer() { // يمكن إرسال البيانات المجمعة بشكل دوري const dataToSend = { ...this.collectedData, anonymousId: this.getAnonymousId(), timestamp: new Date().toISOString() }; // استخدام Beacon API لإرسال البيانات حتى عند إغلاق الصفحة navigator.sendBeacon('/api/collect-data', JSON.stringify(dataToSend)); } // إنشاء معرف مجهول getAnonymousId() { let id = localStorage.getItem('anonymousUserId'); if (!id) { id = 'user_' + Math.random().toString(36).substr(2, 9); localStorage.setItem('anonymousUserId', id); } return id; } // التوقف عن جمع البيانات stopCollection() { this.isCollecting = false; clearInterval(this.sessionInterval); // إرسال البيانات النهائية this.sendToServer(); console.log('توقف جمع البيانات'); } // مسح البيانات المحلية clearLocalData() { localStorage.removeItem('autoCollectedData'); localStorage.removeItem('anonymousUserId'); localStorage.removeItem('lastDataUpdate'); this.collectedData = { demographic: {}, behavioral: {}, technical: {}, preferences: {} }; console.log('تم مسح البيانات المحلية'); } } // استخدام الكود const dataCollector = new AutoDataCollection(); // بدء جمع البيانات عند تحميل الصفحة document.addEventListener('DOMContentLoaded', () => { // تأخير بسيط لتحميل الصفحة أولاً setTimeout(() => { dataCollector.startAutoCollection(); }, 1000); }); // جمع البيانات قبل إغلاق الصفحة window.addEventListener('beforeunload', () => { dataCollector.sendToServer(); }); // إضافة رابط لإدارة الخصوصية function addPrivacyLink() { const privacyLink = document.createElement('a'); privacyLink.href = '/privacy-controls'; privacyLink.textContent = 'إدارة الخصوصية'; privacyLink.style.position = 'fixed'; privacyLink.style.bottom = '10px'; privacyLink.style.left = '10px'; privacyLink.style.zIndex = '10000'; privacyLink.style.background = '#333'; privacyLink.style.color = 'white'; privacyLink.style.padding = '5px 10px'; privacyLink.style.borderRadius = '3px'; privacyLink.style.textDecoration = 'none'; privacyLink.style.fontSize = '12px'; document.body.appendChild(privacyLink); } // تشغيل رابط الخصوصية addPrivacyLink();

0 التعليقات: