Serg4451D commited on
Commit
c183e7a
·
verified ·
1 Parent(s): 709e7b4

Create script.js

Browse files
Files changed (1) hide show
  1. script.js +61 -0
script.js ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ document.addEventListener('DOMContentLoaded', () => {
2
+ const searchInput = document.getElementById('search-input');
3
+ const searchButton = document.getElementById('search-button');
4
+ const resultsContainer = document.getElementById('results');
5
+
6
+ searchButton.addEventListener('click', performSearch);
7
+ searchInput.addEventListener('keypress', (e) => {
8
+ if (e.key === 'Enter') {
9
+ performSearch();
10
+ }
11
+ });
12
+
13
+ async function performSearch() {
14
+ const query = searchInput.value;
15
+ if (!query) return;
16
+
17
+ resultsContainer.innerHTML = '<p>Загрузка результатов...</p>';
18
+
19
+ try {
20
+ const response = await fetch(`https://cors-anywhere.herokuapp.com/https://www.google.com/search?q=${encodeURIComponent(query)}&tbm=search`);
21
+ const html = await response.text();
22
+ const parser = new DOMParser();
23
+ const doc = parser.parseFromString(html, 'text/html');
24
+
25
+ displayResults(doc);
26
+ } catch (error) {
27
+ console.error('Error fetching search results:', error);
28
+ resultsContainer.innerHTML = '<p>Произошла ошибка при поиске. Пожалуйста, попробуйте еще раз.</p>';
29
+ }
30
+ }
31
+
32
+ function displayResults(doc) {
33
+ resultsContainer.innerHTML = '';
34
+
35
+ const searchResults = doc.querySelectorAll('.g');
36
+
37
+ if (searchResults.length === 0) {
38
+ resultsContainer.innerHTML = '<p>Результаты не найдены.</p>';
39
+ return;
40
+ }
41
+
42
+ searchResults.forEach((result, index) => {
43
+ const title = result.querySelector('h3')?.textContent;
44
+ const link = result.querySelector('a')?.href;
45
+ const snippet = result.querySelector('.VwiC3b')?.textContent;
46
+
47
+ if (title && link && snippet) {
48
+ const resultItem = document.createElement('div');
49
+ resultItem.classList.add('result-item');
50
+ resultItem.style.animationDelay = `${index * 0.1}s`;
51
+
52
+ resultItem.innerHTML = `
53
+ <h2><a href="${link}" target="_blank">${title}</a></h2>
54
+ <p>${snippet}</p>
55
+ `;
56
+
57
+ resultsContainer.appendChild(resultItem);
58
+ }
59
+ });
60
+ }
61
+ });