Files
crm.clientright.ru/debug_upload_console.js

252 lines
10 KiB
JavaScript
Raw Normal View History

/**
* Скрипт для отладки загрузки файлов через консоль разработчика
* Добавляет детальное логирование всех этапов загрузки
*/
(function() {
'use strict';
console.log('🔧 DEBUG: Upload monitoring script loaded');
// Перехватываем все AJAX запросы
const originalXHROpen = XMLHttpRequest.prototype.open;
const originalXHRSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
this._debugInfo = {
method: method,
url: url,
startTime: Date.now()
};
if (url.includes('index.php') && method === 'POST') {
console.log('📤 AJAX REQUEST STARTED:', {
method: method,
url: url,
timestamp: new Date().toLocaleTimeString()
});
}
return originalXHROpen.apply(this, arguments);
};
XMLHttpRequest.prototype.send = function(data) {
const xhr = this;
if (this._debugInfo && this._debugInfo.url.includes('index.php')) {
// Логируем данные запроса
if (data instanceof FormData) {
console.log('📋 FORM DATA BEING SENT:');
for (let pair of data.entries()) {
if (pair[1] instanceof File) {
console.log(` ${pair[0]}: FILE - ${pair[1].name} (${pair[1].size} bytes, ${pair[1].type})`);
} else {
console.log(` ${pair[0]}: ${pair[1]}`);
}
}
}
// Перехватываем ответ
const originalOnReadyStateChange = xhr.onreadystatechange;
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
const duration = Date.now() - xhr._debugInfo.startTime;
console.log('📥 AJAX RESPONSE RECEIVED:', {
status: xhr.status,
statusText: xhr.statusText,
duration: duration + 'ms',
responseLength: xhr.responseText ? xhr.responseText.length : 0,
timestamp: new Date().toLocaleTimeString()
});
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
console.log('✅ PARSED RESPONSE:', response);
} catch (e) {
console.log('📄 RAW RESPONSE (first 500 chars):', xhr.responseText.substring(0, 500));
}
} else {
console.error('❌ ERROR RESPONSE:', xhr.responseText);
}
}
if (originalOnReadyStateChange) {
originalOnReadyStateChange.apply(xhr, arguments);
}
};
}
return originalXHRSend.apply(this, arguments);
};
// Перехватываем jQuery AJAX если используется
if (window.jQuery) {
const originalAjax = jQuery.ajax;
jQuery.ajax = function(options) {
if (options.url && options.url.includes('index.php') && options.type === 'POST') {
console.log('🔄 JQUERY AJAX REQUEST:', {
url: options.url,
type: options.type,
data: options.data,
timestamp: new Date().toLocaleTimeString()
});
const originalSuccess = options.success;
const originalError = options.error;
options.success = function(data, textStatus, jqXHR) {
console.log('✅ JQUERY SUCCESS:', {
data: data,
textStatus: textStatus,
timestamp: new Date().toLocaleTimeString()
});
if (originalSuccess) originalSuccess.apply(this, arguments);
};
options.error = function(jqXHR, textStatus, errorThrown) {
console.error('❌ JQUERY ERROR:', {
status: jqXHR.status,
textStatus: textStatus,
errorThrown: errorThrown,
responseText: jqXHR.responseText,
timestamp: new Date().toLocaleTimeString()
});
if (originalError) originalError.apply(this, arguments);
};
}
return originalAjax.apply(this, arguments);
};
}
// Мониторинг изменений в формах загрузки файлов
function monitorFileInputs() {
const fileInputs = document.querySelectorAll('input[type="file"]');
fileInputs.forEach(input => {
if (!input._debugMonitored) {
input._debugMonitored = true;
input.addEventListener('change', function(e) {
const files = e.target.files;
console.log('📁 FILE INPUT CHANGED:', {
inputName: e.target.name,
filesCount: files.length,
files: Array.from(files).map(f => ({
name: f.name,
size: f.size,
type: f.type,
lastModified: new Date(f.lastModified).toLocaleString()
})),
timestamp: new Date().toLocaleTimeString()
});
});
}
});
}
// Мониторинг отправки форм
function monitorFormSubmissions() {
const forms = document.querySelectorAll('form');
forms.forEach(form => {
if (!form._debugMonitored) {
form._debugMonitored = true;
form.addEventListener('submit', function(e) {
console.log('📝 FORM SUBMISSION:', {
formName: form.name || 'unnamed',
action: form.action,
method: form.method,
enctype: form.enctype,
timestamp: new Date().toLocaleTimeString()
});
// Логируем все поля формы
const formData = new FormData(form);
console.log('📋 FORM FIELDS:');
for (let pair of formData.entries()) {
if (pair[1] instanceof File) {
console.log(` ${pair[0]}: FILE - ${pair[1].name} (${pair[1].size} bytes)`);
} else {
console.log(` ${pair[0]}: ${pair[1]}`);
}
}
});
}
});
}
// Запускаем мониторинг каждые 2 секунды для новых элементов
setInterval(() => {
monitorFileInputs();
monitorFormSubmissions();
}, 2000);
// Начальный запуск
monitorFileInputs();
monitorFormSubmissions();
// Добавляем глобальные функции для ручной отладки
window.debugUpload = {
logCurrentForms: function() {
const forms = document.querySelectorAll('form');
console.log('📋 CURRENT FORMS ON PAGE:', Array.from(forms).map(f => ({
name: f.name,
action: f.action,
method: f.method,
enctype: f.enctype,
fields: Array.from(f.elements).map(el => ({
name: el.name,
type: el.type,
value: el.type === 'file' ? `FILE: ${el.files.length} files` : el.value
}))
})));
},
logFileInputs: function() {
const inputs = document.querySelectorAll('input[type="file"]');
console.log('📁 FILE INPUTS:', Array.from(inputs).map(input => ({
name: input.name,
files: Array.from(input.files).map(f => ({
name: f.name,
size: f.size,
type: f.type
}))
})));
},
testUpload: function(filename = 'test.txt') {
console.log('🧪 TESTING UPLOAD WITH:', filename);
// Создаем тестовый файл
const testContent = 'Test file content - ' + new Date().toISOString();
const testFile = new File([testContent], filename, { type: 'text/plain' });
// Ищем форму загрузки
const uploadForm = document.querySelector('form[name="upload"]') || document.querySelector('form');
if (uploadForm) {
const fileInput = uploadForm.querySelector('input[type="file"]');
if (fileInput) {
// Имитируем выбор файла
const dt = new DataTransfer();
dt.items.add(testFile);
fileInput.files = dt.files;
// Запускаем событие change
fileInput.dispatchEvent(new Event('change', { bubbles: true }));
console.log('✅ Test file added to input');
} else {
console.error('❌ No file input found in form');
}
} else {
console.error('❌ No upload form found');
}
}
};
console.log('🎯 DEBUG FUNCTIONS AVAILABLE:');
console.log(' debugUpload.logCurrentForms() - показать все формы');
console.log(' debugUpload.logFileInputs() - показать файловые поля');
console.log(' debugUpload.testUpload() - тестовая загрузка');
})();