Search code examples
javascriptsearchsearchbargoogle-search-api

How to get the same predictive search data that shows under the google search bar


I'm trying to find a way to get the same predictive search results that shows under the Google search bar as your typing. I'm not talking about custom search for a specific site either. I thought this wasn't possible until I came across a new tab page extension from the chrome store.

https://chrome.google.com/webstore/detail/start-a-better-new-tab/kgifkabikplflflabkllnpidlbjjpgbp?hl=en

Their search bar predictions matches Google's exactly. What source are they getting that data from? Are there any other predictive search services/APIs that anyone can recommend?


Solution

  • "What source are they getting that data from?"

    By looking at the extension's source code, this URL:
    https://google.com/complete/search?client=firefox&hl=en&q=foo

    It's the same API that Google uses on its search page. But that API is protected by CORS policy, so it can't be accessed from any webpage. A browser extension can, because it's granted more rights. To use it, you would need a proxy server (either your own, or a free one, such as the one in the example below).

    const searchInput = document.getElementById('search'),
      suggestionsList = document.getElementById('suggestions');
    
    searchInput.addEventListener('input', autocomplete);
    autocomplete();
    
    function autocomplete() {
      const q = searchInput.value;
      const proxy = 'https://cors-everywhere.herokuapp.com/';
      
      fetch(`${proxy}https://google.com/complete/search?client=firefox&hl=en&q=${q}`, {
        headers: { origin: 'google.com' }
      })
      .then(res => res.json())
      .then(res => {
        suggestionsList.innerHTML = res[1].map(x => `<li>${x}</li>`).join('')
      });
    }
    <input id="search" value="foo" />
    <ul id="suggestions"></ul>

    "Are there any other ... services/APIs?"

    We can't answer that here, as it's off-topic. This type of questions tend to attract opinionated answers and spam.