test2 / index.html
usmv3131's picture
нужно отправлять данные на вебхук https://obigoolooleg.beget.app/webhook-test/41bb43f2-9bed-4e49-bbc5-e90e6f7f2138 - Initial Deployment
6c35361 verified
Raw
History Blame Contribute Delete
7.21 kB
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Webhook Client</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: #f5f5f5;
}
.container {
background: white;
padding: 25px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
h2 {
color: #333;
margin-top: 0;
}
textarea {
width: 100%;
min-height: 100px;
padding: 12px;
border: 1px solid #ddd;
border-radius: 4px;
resize: vertical;
font-family: inherit;
box-sizing: border-box;
}
button {
padding: 12px 24px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
.status {
padding: 12px;
border-radius: 4px;
margin: 15px 0;
font-weight: 500;
}
.waiting {
background-color: #e3f2fd;
color: #1565c0;
}
.sending {
background-color: #fff3e0;
color: #ef6c00;
}
.success {
background-color: #e8f5e9;
color: #2e7d32;
}
.error {
background-color: #ffebee;
color: #c62828;
}
.info {
margin-top: 20px;
padding: 15px;
background-color: #f5f5f5;
border-left: 4px solid #2196f3;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<h2>Webhook Client</h2>
<textarea id="inputData" placeholder="Введите данные для отправки (JSON или текст)..."></textarea>
<button id="sendButton" onclick="sendData()">Отправить</button>
<div class="status waiting" id="status">Статус: Ожидание действий...</div>
<h3>Ответ от сервера:</h3>
<textarea id="outputResponse" readonly placeholder="Здесь появится ответ..."></textarea>
<div class="info" id="infoBox">
<strong>Информация:</strong> Если возникает ошибка "Failed to fetch", это может быть связано с:
<ul>
<li>Проблемами CORS на сервере</li>
<li>Блокировкой запроса расширениями браузера</li>
<li>Неточностью в URL вебхука</li>
</ul>
</div>
</div>
<script>
const sendButton = document.getElementById('sendButton');
const inputElement = document.getElementById('inputData');
const outputElement = document.getElementById('outputResponse');
const statusElement = document.getElementById('status');
const infoBox = document.getElementById('infoBox');
async function sendData() {
const data = inputElement.value.trim();
// Очистка предыдущего статуса
infoBox.style.display = 'none';
if (!data) {
showStatus('error', 'Ошибка: пустой ввод');
return;
}
try {
// Блокируем кнопку на время отправки
sendButton.disabled = true;
showStatus('sending', 'Статус: Отправка данных...');
const response = await fetchWithTimeout(
'https://obigoolooleg.beget.app/webhook-test/41bb43f2-9bed-4e49-bbc5-e90e6f7f2138',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: data,
timestamp: new Date().toISOString()
})
},
10000 // 10 секунд таймаут
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const responseData = await response.text();
outputElement.value = responseData;
showStatus('success', 'Статус: Успешно отправлено!');
} catch (error) {
console.error('Ошибка:', error);
// Анализ типа ошибки
if (error.name === 'TypeError' && error.message === 'Failed to fetch') {
showStatus('error', 'Ошибка: Не удалось подключиться к серверу (Failed to fetch)');
infoBox.style.display = 'block';
} else if (error.name === 'AbortError') {
showStatus('error', 'Ошибка: Превышено время ожидания ответа сервера');
} else {
showStatus('error', 'Ошибка: ' + error.message);
}
outputElement.value = '';
} finally {
sendButton.disabled = false;
}
}
// Функция для выполнения fetch с таймаутом
async function fetchWithTimeout(url, options, timeout) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal: controller.signal
});
clearTimeout(id);
return response;
} catch (error) {
clearTimeout(id);
throw error;
}
}
// Функция для отображения статуса
function showStatus(type, message) {
statusElement.textContent = message;
statusElement.className = 'status ' + type;
}
// Добавляем возможность отправки по Enter
inputElement.addEventListener('keypress', function(e) {
if (e.key === 'Enter' && e.ctrlKey) {
sendData();
}
});
</script>
</body>
</html>