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
, 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:
- "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
- "Public URL" will show you a work preview of the set search
- "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 id="GCSE-test">GCSE test</h1> <div id="searchForm" class="gcse-search-wrapper"></div> <div id="searchResults" class="gcse-results-wrapper"></div> <🎜> </body> </html>
We added two <div> and used special classes to identify elements where the search form and results should be presented.
<p><strong>Manual rendering function</strong></p>
<p>Now enter your app.js file and add the following: </p>
<pre class='brush:php;toolbar:false;'>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);
})();
</pre>
<p>First, we declare some variables for configuration. Put the ID you wrote down before into the <code>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.
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 };
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.
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 id="GCSE-test">GCSE test</h1> <div id="searchForm" class="gcse-search-wrapper"></div> <div id="searchResults" class="gcse-results-wrapper"></div> <🎜> </body> </html>
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); })();
Now try loading the test page again and you will see the correct placeholder.
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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.