Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a website highlight search terms you used in the search engine?

I've seen some websites highlight the search engine keywords you used, to reach the page. (such as the keywords you typed in the Google search listing)

How does it know what keywords you typed in the search engine? Does it examine the referrer HTTP header or something? Any available scripts that can do this? It might be server-side or JavaScript, I'm not sure.

like image 865
Robin Rodricks Avatar asked May 25 '09 16:05

Robin Rodricks


People also ask

How do I highlight search terms in Google?

Simply navigate to a web page, then, open toolbar popup UI and type your keyword in the designated area. Then click on the "Find" button or press "Enter" on your keyboard. All the matching words within the web page will be highlighted with yellow color.

How do I highlight search results in HTML?

The <mark> HTML element is used to highlight text, so is the perfect element for this use case.

How does Google highlight work?

The feature works with Google's Featured Snippets, which appear at the top of search results. Clicking a snippet takes the user to the source webpage, but now the browser automatically scrolls down the page to the text that appeared in the snippet and highlights it in yellow.

Why does Google highlight in yellow?

Google is trying to make it easier to find the information you're looking for on external websites by highlighting relevant sections in yellow, SearchEngineLand reports.


1 Answers

This can be done either server-side or client-side. The search keywords are determined by looking at the HTTP Referer (sic) header. In JavaScript you can look at document.referrer.

Once you have the referrer, you check to see if it's a search engine results page you know about, and then parse out the search terms.

For example, Google's search results have URLs that look like this:

http://www.google.com/search?hl=en&q=programming+questions

The q query parameter is the search query, so you'd want to pull that out and un-URL-escape it, resulting in:

programming questions

Then you can search for the terms on your page and highlight them as necessary. If you're doing this server side-you'd modify the HTML before sending it to the client. If you're doing it client-side you'd manipulate the DOM.

There are existing libraries that can do this for you, like this one.

like image 158
Laurence Gonsalves Avatar answered Oct 09 '22 03:10

Laurence Gonsalves