File size: 6,515 Bytes
317f1fb
13c86d9
317f1fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13c86d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Brave News Search Example</title>
    <style>
      /* Simple styling (optional) */
      body { font-family: sans-serif; margin: 20px; }
      form > div { margin-bottom: 8px; }
      label { font-weight: bold; margin-right: 5px; }
    </style>
  </head>
  <body>
    <h1>Brave News Search</h1>
    <form id="searchForm">
      <div>
        <label for="query">Query:</label>
        <input type="text" id="query" name="query" required />
      </div>
      <div>
        <label for="country">Country:</label>
        <select id="country" name="country">
          <option value="us">United States (US)</option>
          <option value="gb">United Kingdom (GB)</option>
          <option value="ca">Canada (CA)</option>
          <option value="all">All Regions (ALL)</option>
          <!-- ...other country options as needed... -->
        </select>
      </div>
      <div>
        <label for="language">Language:</label>
        <select id="language" name="language">
          <option value="en">English (en)</option>
          <option value="es">Spanish (es)</option>
          <option value="fr">French (fr)</option>
          <!-- ...other language options as needed... -->
        </select>
      </div>
      <div>
        <label for="safesearch">SafeSearch:</label>
        <select id="safesearch" name="safesearch">
          <option value="moderate">Moderate (default)</option>
          <option value="off">Off</option>
          <option value="strict">Strict</option>
        </select>
      </div>
      <div>
        <label for="freshness">Freshness:</label>
        <select id="freshness" name="freshness" onchange="toggleDateInputs()">
          <option value="">Any time (no filter)</option>
          <option value="pd">Last 24 hours</option>
          <option value="pw">Past week</option>
          <option value="pm">Past month</option>
          <option value="py">Past year</option>
          <option value="custom">Custom range...</option>
        </select>
      </div>
      <div id="customDateRange" style="display:none; margin-left: 20px;">
        <label for="fromDate">From:</label>
        <input type="date" id="fromDate" name="fromDate" /> 
        <label for="toDate">To:</label>
        <input type="date" id="toDate" name="toDate" />
      </div>
      <button type="submit">Search</button>
    </form>

    <div id="results"></div>  <!-- Container to display results -->

    <script>
      const API_KEY = 'YOUR_API_KEY_HERE';  // TODO: replace with your Brave API key

      // Show/hide custom date inputs based on selection
      function toggleDateInputs() {
        const freshnessValue = document.getElementById('freshness').value;
        const customRangeDiv = document.getElementById('customDateRange');
        if (freshnessValue === 'custom') {
          customRangeDiv.style.display = 'block';
        } else {
          customRangeDiv.style.display = 'none';
        }
      }

      // Handle form submission to perform the API search
      document.getElementById('searchForm').addEventListener('submit', function(event) {
        event.preventDefault();  // prevent page reload

        // Gather input values
        const query = document.getElementById('query').value.trim();
        const country = document.getElementById('country').value;       // e.g. "us"
        const language = document.getElementById('language').value;     // e.g. "en"
        const safesearch = document.getElementById('safesearch').value; // "off", "moderate", or "strict"
        const freshnessSelection = document.getElementById('freshness').value;

        // Build the freshness parameter if needed
        let freshnessParam = "";
        if (freshnessSelection === 'custom') {
          // If custom range, format as YYYY-MM-DDtoYYYY-MM-DD
          const fromDate = document.getElementById('fromDate').value;
          const toDate = document.getElementById('toDate').value;
          if (fromDate && toDate) {
            freshnessParam = `${fromDate}to${toDate}`;  
          } else {
            freshnessParam = "";  // if dates not fully specified, treat as no filter
          }
        } else if (freshnessSelection !== "") {
          // If a preset like 'pd','pw','pm','py' is selected
          freshnessParam = freshnessSelection;
        }
        // (If freshnessSelection is empty or "Any time", we leave freshnessParam blank to not apply any time filter)

        // Construct query parameters
        const params = new URLSearchParams();
        params.append('q', query);
        params.append('country', country);
        params.append('search_lang', language);
        params.append('safesearch', safesearch);
        if (freshnessParam) {
          params.append('freshness', freshnessParam);
        }
        // (We could append 'count' or other parameters here if needed. By default, 20 results are returned.)

        // Set up request headers including API key
        const headers = {
          'Accept': 'application/json',
          'Accept-Encoding': 'gzip',
          'X-Subscription-Token': API_KEY
        };

        // Perform the fetch call to Brave News Search API
        fetch(`https://api.search.brave.com/res/v1/news/search?${params.toString()}`, { headers: headers })
          .then(response => {
            if (!response.ok) {
              throw new Error(`API request failed with status ${response.status}`);
            }
            return response.json();
          })
          .then(data => {
            console.log("API response:", data);
            // Display results on the page (simple example)
            const resultsDiv = document.getElementById('results');
            resultsDiv.innerHTML = "";  // clear previous results
            if (data.news && data.news.results) {
              data.news.results.forEach(item => {
                const p = document.createElement('p');
                p.innerHTML = `<a href="${item.url}" target="_blank">${item.title}</a><br><small>${item.source.name}${item.date}</small>`;
                resultsDiv.appendChild(p);
              });
            } else {
              resultsDiv.textContent = "No results found.";
            }
          })
          .catch(error => {
            console.error("Error fetching search results:", error);
            document.getElementById('results').textContent = "Error: " + error.message;
          });
      });
    </script>
  </body>
</html>