// Расширенная версия с дополнительными возможностями class UrlParamsManager { constructor() { this.utmKeys = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']; this.otherKeys = ['ref', 'source', 'gclid', 'yclid', 'fbclid', 'roistat', 'from']; this.allKeys = [...this.utmKeys, ...this.otherKeys]; this.init(); } init() { this.saveParams(); this.addParamsToForms(); this.modifyLinks(); this.setCookies(); } // Получение всех параметров из URL getAllParams() { const params = new URLSearchParams(window.location.search); const result = {}; this.allKeys.forEach(key => { const value = params.get(key); if (value) { result[key] = value; } }); return result; } // Сохранение параметров saveParams() { const params = this.getAllParams(); if (Object.keys(params).length > 0) { // SessionStorage sessionStorage.setItem('urlParams', JSON.stringify(params)); // LocalStorage const existing = JSON.parse(localStorage.getItem('urlParams') || '{}'); localStorage.setItem('urlParams', JSON.stringify({...existing, ...params})); console.log('UTM-параметры сохранены:', params); } } // Получение сохраненных параметров getParams() { try { const session = JSON.parse(sessionStorage.getItem('urlParams') || '{}'); const local = JSON.parse(localStorage.getItem('urlParams') || '{}'); return {...local, ...session}; } catch (e) { return {}; } } // Добавление параметров к формам addParamsToForms() { setTimeout(() => { const forms = document.querySelectorAll('form'); const params = this.getParams(); forms.forEach(form => { Object.keys(params).forEach(key => { if (!form.querySelector(`[name="${key}"]`)) { const input = document.createElement('input'); input.type = 'hidden'; input.name = key; input.value = params[key]; form.appendChild(input); } }); }); }, 1500); } // Модификация ссылок (опционально) modifyLinks() { document.addEventListener('click', (e) => { const link = e.target.closest('a'); if (link && link.href) { const params = this.getParams(); if (Object.keys(params).length > 0) { const url = new URL(link.href); Object.keys(params).forEach(key => { if (!url.searchParams.has(key)) { url.searchParams.set(key, params[key]); } }); link.href = url.toString(); } } }); } // Сохранение в cookies (на 30 дней) setCookies() { const params = this.getParams(); Object.keys(params).forEach(key => { const value = params[key]; const date = new Date(); date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 дней document.cookie = `${key}=${value}; expires=${date.toUTCString()}; path=/; SameSite=Lax`; }); } // Получение конкретного параметра getParam(name) { const params = this.getParams(); return params[name] || null; } // Получение всех параметров как строку getParamsString() { const params = this.getParams(); return new URLSearchParams(params).toString(); } } // Инициализация при загрузке страницы document.addEventListener('DOMContentLoaded', function() { window.urlParamsManager = new UrlParamsManager(); // Пример использования в консоли: // window.urlParamsManager.getParam('utm_source') // window.urlParamsManager.getParams() });
Не нужно тратить время на поиски информации
Бери проверенные знания и получай результат
3 990₽