Home > Web Front-end > JS Tutorial > Quick Tip: How to Style Google Custom Search Manually

Quick Tip: How to Style Google Custom Search Manually

Jennifer Aniston
Release: 2025-02-17 09:42:10
Original
827 people have browsed it

Quick Tip: How to Style Google Custom Search Manually

Core points

  • By manually rendering search forms (without the need to use special GCSE tags), you can manually style Google Custom Search Engine (GCSE), thereby giving you better control over the search input fields and making them look simpler.
  • GCSE callback function ensures that the input is loaded before changing the input properties. This method is more reliable than using the setTimeout method.
  • The Google Search API can be used to create search boxes and result boxes. If an active query exists, a result box is also created. Other customizations can be achieved by looking up the document.
  • Custom style functions can be added to the search div for further customization. This function can be used to change placeholders, delete backgrounds, and add events that remove backgrounds when out of focus.

This article was reviewed by Mark Brown. Thanks to all the peer reviewers at SitePoint for getting SitePoint content to its best!

Website owners often choose to use Google Custom Search Engine (GCSE) to search for their content instead of using built-in and/or custom search features. The reason is simple - much less work and in most cases it can achieve the purpose. If you don't need advanced filters or custom search parameters, GCSE is for you.

In this quick tip, I will show you how to manually render the search form (no need to use special GCSE tags) and result boxes, which allow for finer control and a cleaner search input field Style setting method.

Question

Usually, adding GCSE to your website is as easy as copy-pasting scripts and custom HTML tags to your website. Where you place the special GCSE tag, an input search field will be rendered. Type and start search from this field will perform a Google search based on previously configured parameters (for example, search only sitepoint.com).

A common question is "How to change the placeholder for the GCSE input field?". Unfortunately, the suggested answer is usually wrong, as it uses the unreliable

method to wait for the Ajax call of GCSE to complete (make sure the input is attached to the DOM), and then change the properties via JavaScript. setTimeout

We will also query elements and change attributes using JS, but we will use the callback function provided by GCSE instead of blindly using

, which will ensure that the input is loaded. setTimeout()

Create a GCSE account

Search engine is fully configured online. The first step is to go to the GCSE website and click Add. Follow the wizard to fill in the domain name you want to search for (usually your website URL). Now you can ignore any advanced settings.

After clicking "Finish", you will see three options:

  1. "Get Code", which will guide you through what you have to copy and where to place it so that the search will appear on your website
  2. "Public URL" will show you a work preview of the set search
  3. "Control Panel" is used to customize searches

Go to Control Panel, click Search Engine ID, and note this value for later use.

HTML Settings

To try it out, we will create a basic index.html with the required HTML, as well as an app.js file that contains the functions required for rendering and custom search.

Continue to create a basic HTML file with:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GCSE test</title>
</head>
<body>

    <h1>GCSE test</h1>
    <div id="searchForm" class="gcse-search-wrapper"></div>
    <div id="searchResults" class="gcse-results-wrapper"></div>
    <🎜>

</body>
</html>
Copy after login
Copy after login

We added two <div> and used special classes to identify elements where the search form and results should be presented.

Manual rendering function

Now enter your app.js file and add the following:

var config = {
  gcseId: '006267341911716099344:r_iziouh0nw', // 替换为您的搜索引擎ID
  resultsUrl: 'http://localhost:8080', // 替换为您的本地服务器地址
  searchWrapperClass: 'gcse-search-wrapper',
  resultsWrapperClass: 'gcse-results-wrapper'
};

var renderSearchForms = function () {
  if (document.readyState == 'complete') {
    queryAndRender();
  } else {
    google.setOnLoadCallback(function () {
      queryAndRender();
    }, true);
  }
};

var queryAndRender = function() {
  var gsceSearchForms = document.querySelectorAll('.' + config.searchWrapperClass);
  var gsceResults = document.querySelectorAll('.' + config.resultsWrapperClass);

  if (gsceSearchForms.length > 0) {
    renderSearch(gsceSearchForms[0]);
  }
  if (gsceResults.length > 0) {
    renderResults(gsceResults[0]);
  }
};

var renderSearch = function (div) {
    google.search.cse.element.render(
      {
        div: div.id,
        tag: 'searchbox-only',
        attributes: {
          resultsUrl: config.resultsUrl
        }
      }
    );
    if (div.dataset &&
        div.dataset.stylingFunction &&
        window[div.dataset.stylingFunction] &&
        typeof window[div.dataset.stylingFunction] === 'function') {
      window[div.dataset.stylingFunction](div); // 传递div而不是form
    }
};

var renderResults = function(div) {
  google.search.cse.element.render(
    {
      div: div.id,
      tag: 'searchresults-only'
    });
};

window.__gcse = {
  parsetags: 'explicit',
  callback: renderSearchForms
};

(function () {
  var cx = config.gcseId;
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
    '//cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();
Copy after login
Copy after login

First, we declare some variables for configuration. Put the ID you wrote down before into the gcseId field of config. Put the URL of the local index.html file into the resultsUrl field. This is where the search will be redirected to after the user submits the query. Additionally, GCSE will expect to render the result field on the provided URL.

renderSearchForms function checks if the page is loaded, and if it is loaded, the callback function will be responsible for rendering queryAndRender(); or, if the document has not been loaded, set up a callback function to return this later after the document is loaded. place.

queryAndRender function query the DOM with elements of the class provided in config. If the wrapper div is found, renderSearch() and renderResults() are called respectively to render the search and result fields.

renderSearch Functions are where actual magic happens.

We use the Google Search API (more documentation here on how to use the google.search.cse.element object) to create the search box and if there is an active query (result) then the result box is created.

The

render function accepts more parameters than is provided in this example, so be sure to check the documentation if further customization is required. The div parameter actually accepts the ID of the div we are going to render, and the tag parameter indicates what exactly we are going to render ( results or search or both).

In addition, renderSearch() finds the data attribute of the wrapper element, and if the styling-function attribute is given, it will look for the function name in the scope and apply it to the element. This is our chance to style the element.

window.__gcse = {
  parsetags: 'explicit',
  callback: renderSearchForms
};
Copy after login

In this code snippet, we set a callback variable in the global scope so that GCSE can use this variable internally and execute the callback function after loading is complete. This makes this method much better than using the setTimeout() solution to edit the placeholder (or anything else) of the input field.

Test run

So far, we have included everything we need to render the search box and the results. If you have node.js installed, go to the folder where the index.html and app.js files are placed and run the http-server command. By default, this will provide the contents in the folder on port 8080 on localhost.

Quick Tip: How to Style Google Custom Search Manually

Style function

Now we are going to add custom style functions to the search div. Return index.html and add a #searchForm attribute on the styling-function div:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>GCSE test</title>
</head>
<body>

    <h1>GCSE test</h1>
    <div id="searchForm" class="gcse-search-wrapper"></div>
    <div id="searchResults" class="gcse-results-wrapper"></div>
    <🎜>

</body>
</html>
Copy after login
Copy after login

Now go to app.js, at the top of the file, under the config variable declaration, add a new function:

var config = {
  gcseId: '006267341911716099344:r_iziouh0nw', // 替换为您的搜索引擎ID
  resultsUrl: 'http://localhost:8080', // 替换为您的本地服务器地址
  searchWrapperClass: 'gcse-search-wrapper',
  resultsWrapperClass: 'gcse-results-wrapper'
};

var renderSearchForms = function () {
  if (document.readyState == 'complete') {
    queryAndRender();
  } else {
    google.setOnLoadCallback(function () {
      queryAndRender();
    }, true);
  }
};

var queryAndRender = function() {
  var gsceSearchForms = document.querySelectorAll('.' + config.searchWrapperClass);
  var gsceResults = document.querySelectorAll('.' + config.resultsWrapperClass);

  if (gsceSearchForms.length > 0) {
    renderSearch(gsceSearchForms[0]);
  }
  if (gsceResults.length > 0) {
    renderResults(gsceResults[0]);
  }
};

var renderSearch = function (div) {
    google.search.cse.element.render(
      {
        div: div.id,
        tag: 'searchbox-only',
        attributes: {
          resultsUrl: config.resultsUrl
        }
      }
    );
    if (div.dataset &&
        div.dataset.stylingFunction &&
        window[div.dataset.stylingFunction] &&
        typeof window[div.dataset.stylingFunction] === 'function') {
      window[div.dataset.stylingFunction](div); // 传递div而不是form
    }
};

var renderResults = function(div) {
  google.search.cse.element.render(
    {
      div: div.id,
      tag: 'searchresults-only'
    });
};

window.__gcse = {
  parsetags: 'explicit',
  callback: renderSearchForms
};

(function () {
  var cx = config.gcseId;
  var gcse = document.createElement('script');
  gcse.type = 'text/javascript';
  gcse.async = true;
  gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
    '//cse.google.com/cse.js?cx=' + cx;
  var s = document.getElementsByTagName('script')[0];
  s.parentNode.insertBefore(gcse, s);
})();
Copy after login
Copy after login

Now try loading the test page again and you will see the correct placeholder.

Quick Tip: How to Style Google Custom Search Manually

Conclusion

Google custom search engines are very effective for quick setup of simple searches, especially when the website is just static HTML. With just a small amount of JavaScript code, you can customize search forms and result pages to provide users with a more seamless experience.

Are you using GCSE, or have you found a better solution? Please comment below!

FAQ on setting Google's custom search styles

How to customize the appearance of Google's custom search engine?

Customize the appearance of custom Google search engines involving the use of CSS (cascading stylesheets). CSS is a stylesheet language that describes the appearance and formatting of documents written in HTML. You can change the color, font, size, and other elements of search engines. To do this, you need to access the Programmable Search Element Control API, which allows you to customize search elements. You can then add CSS to the correct section to change the look of the search engine.

Can I add Google custom search to my website?

Yes, you can add Google custom searches to your website. Google provides a custom search JSON API that you can use to send GET requests. This API returns search results in JSON format. You can then use these results to create a custom search engine on your website. This allows your users to search for your website or other websites you specify.

How to implement the search box using Google Custom Search?

Implementing a search box with Google Custom Search involves creating a search engine ID, which you can do on a programmable search engine website. Once you have the ID, you can use the Custom Search Element Control API to create a search box. You can then customize this search box using CSS.

What is the programmable search element control API?

The Programmable Search Element Control API is a set of functions provided by Google that allows you to customize programmable search engines. This includes creating search boxes, customizing the look of search engines, and controlling search results.

How to control search results in Google Custom Search?

You can use the Programmable Search Element Control API to control search results in Google's custom searches. This API provides functions that allow you to specify the website you searched, the number of results returned, and the order in which results are displayed.

Can I use Google Custom Search for commercial purposes?

Yes, you can use Google custom searches for commercial purposes. However, you need to understand the terms of service. For example, you cannot use search engines to display adult content or promote illegal activities.

How to change the color of search results in Google Custom Search?

You can use CSS to change the color of search results in Google's custom search. You need to access the programmable search element control API and add CSS to the correct section. You can change the colors of text, background, and other search result elements.

Can I use Google to custom search on my mobile device?

Yes, you can customize searches using Google on your mobile device. The programmable search engine is designed to be responsive, which means it will adjust to fit the screen size of the device it is viewing. You can also use CSS to customize the look of the search engine to make it more mobile-friendly.

How to add a logo in my Google custom search engine?

You can add logos in my Google custom search engine using CSS. You need to access the programmable search element control API and add CSS to the correct section. You can then add an image URL to display as your logo.

Can I use Google to custom search without coding knowledge?

While you can use Google to customize searches without coding knowledge, it is recommended that you have a certain understanding of HTML and CSS to fully customize your search engine. However, Google provides detailed documentation and tutorials to get you started.

The above is the detailed content of Quick Tip: How to Style Google Custom Search Manually. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template