How to integrate google site search into our own website

When we want to search something in a specific website, we can utilize google's :site keyword.

For example, type logging site:python.org in google's search box, and you will get logging related stuff on python.org.

According to this method, we can integrate google site search into our own website.

Integrate with a website

Assume that you are the developer of example.com, and you want add a search box on example.com so that users can search things on example.com.

First, add a search box to your page's html:

<form id="search-form">
    <input id="searchbox" placeholder="Search" aria-label="Search">
    <button type="submit">Search</button>
</form>

Then, add js script:

document.getElementById('search-form').addEventListener('submit', function(event) {
    event.preventDefault();  // to stop form being submitted
    let keyword = document.getElementById('searchbox').value;  // user's raw input
    // use "site:example.com" to tell google that you only want results from example.com
    window.location = 'https://www.google.com/search?q=' + keyword + ' site:example.com'
})
Posted on 2022-03-29