back

by m-i-l·5y ago·view on hn ↗
Looks nice, but as you say that just searches the current page. Here's how I search my entire site with slightly fewer lines of JavaScript:

  // Construct the API query
  const apiEndpoint = 'https://searchmysite.net/api/v1/search/michael-lewis.com';
  let urlParams = new URLSearchParams(window.location.search);
  let queryParam = urlParams.get('q');
  if (queryParam == null || queryParam == '') { queryParam = '*' }
  let apiQuery = apiEndpoint.concat('?q=', queryParam);

  // Build the results (using fetch rather than XMLHttpRequest)
  fetch(apiQuery)
    .then((resp) => resp.json()) 
    .then(function(data) {
      let searchResults = data.results;
      document.getElementById('query').value = queryParam; // Set the value of the search box to the query
      if (searchResults && searchResults.length > 0) {
        return searchResults.map(function(result) {
          // Each result is going to be displayed as <li><a href="${result.url}" class="title">${result.title}</a></li>
          let li = document.createElement('li'), a = document.createElement('a');
          a.appendChild(document.createTextNode(`${result.title}`));
          a.href = `${result.url}`;
          a.classList.add('title');
          li.appendChild(a);
          // Each result is added to the <ul id="results"></ul>
          document.getElementById('results').appendChild(li);
        })
      }
      else {
        // If there are no results update the <h1 class="title" id="results-title">Results</h1>
        document.getElementById('results-title').innerText = 'No results';
      }
    })
    .catch(function(error) {
      console.log(error);
    });