news-html / index.html
yokoha's picture
Update index.html
317f1fb verified
<!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>