How to add Google/Bing Search to your web page?

Let’s say you have created a website.

And you want your users to be able to do Google search or Bing search within your website.

How do you do that?

Just by including the below code:

For Google search:

<form action="https://www.google.com/search" method="get">
 <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>

For Bing search:

<form action="https://www.bing.com/search" method="get">
 <label>Bing: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>

The above two are basically html forms which make “GET” requests to the search API of Google and Bing respectively. The search parameter is specified with the input name “q” in both the cases.

In both the above cases , the search results open in the same tab.

To open it in a different tab , use the target attribute within the form:

<form action="https://www.google.com/search" method="get" target="_blank">
 <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>

Now a new tab opens up with the Google search results on clicking “Search…” button.

How to do Google search on a single website?

Let’s say you want to tell Google to search only one website.

You can implement this by using a hidden attribute named “sitesearch” and specifying the URL of the website you want to search as its value.

Example:

<form action="https://www.google.com/search" method="get" target="_blank">
 <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search...">
 <input type="hidden" name="sitesearch" value="https://fullstackdeveloper.guru" />
</form>

In the above case I am directing Google to search within my website.

Example, when I key in the word “spring boot”, here is how the results are displayed:

That’s it!

Ref: https://html.spec.whatwg.org/dev/forms.html#forms


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading