| document.addEventListener('DOMContentLoaded', () => { |
| const searchInput = document.getElementById('search-input'); |
| const searchButton = document.getElementById('search-button'); |
| const resultsContainer = document.getElementById('results'); |
|
|
| searchButton.addEventListener('click', performSearch); |
| searchInput.addEventListener('keypress', (e) => { |
| if (e.key === 'Enter') { |
| performSearch(); |
| } |
| }); |
|
|
| async function performSearch() { |
| const query = searchInput.value; |
| if (!query) return; |
|
|
| resultsContainer.innerHTML = '<p>Загрузка результатов...</p>'; |
|
|
| try { |
| const response = await fetch(`https://cors-anywhere.herokuapp.com/https://www.google.com/search?q=${encodeURIComponent(query)}&tbm=search`); |
| const html = await response.text(); |
| const parser = new DOMParser(); |
| const doc = parser.parseFromString(html, 'text/html'); |
|
|
| displayResults(doc); |
| } catch (error) { |
| console.error('Error fetching search results:', error); |
| resultsContainer.innerHTML = '<p>Произошла ошибка при поиске. Пожалуйста, попробуйте еще раз.</p>'; |
| } |
| } |
|
|
| function displayResults(doc) { |
| resultsContainer.innerHTML = ''; |
|
|
| const searchResults = doc.querySelectorAll('.g'); |
|
|
| if (searchResults.length === 0) { |
| resultsContainer.innerHTML = '<p>Результаты не найдены.</p>'; |
| return; |
| } |
|
|
| searchResults.forEach((result, index) => { |
| const title = result.querySelector('h3')?.textContent; |
| const link = result.querySelector('a')?.href; |
| const snippet = result.querySelector('.VwiC3b')?.textContent; |
|
|
| if (title && link && snippet) { |
| const resultItem = document.createElement('div'); |
| resultItem.classList.add('result-item'); |
| resultItem.style.animationDelay = `${index * 0.1}s`; |
|
|
| resultItem.innerHTML = ` |
| <h2><a href="${link}" target="_blank">${title}</a></h2> |
| <p>${snippet}</p> |
| `; |
|
|
| resultsContainer.appendChild(resultItem); |
| } |
| }); |
| } |
| }); |