Skip to Content

tryGCSESearch()

Run a search through Google Custom Search Engine for the website.

JavaScript February 7, 2021

Usage

JavaScript
nebula.tryGCSESearch(phrase)

Parameters

phrase
(Required) (String) The keyphrase to search Google for
Default: None

Request or provide clarification »

Additional Notes

Both the Google Custom Search Engine ID and Google Browser API Key are required in Nebula Options.

This search will only search the current site, but the results are external (from Google’s indexes) rather than internal (WordPress DB).

Source File

Located in /assets/js/modules/search.js on line 402.

No Hooks

This function does not have any filters or actions available. Request one?
JavaScript
nebula.tryGCSESearch = function(phrase){
    if ( nebula.site.options.nebula_cse_id.length && nebula.site.options.nebula_google_browser_api_key.length ){
        let queryParams = {
            cx: nebula.site.options.nebula_cse_id,
            key: nebula.site.options.nebula_google_browser_api_key,
            num: 10,
            q: phrase,
            alt: 'JSON'
        };
        const API_URL = 'https://www.googleapis.com/customsearch/v1?';

        //Send the request to the custom search API
        jQuery.getJSON(API_URL, queryParams, function(response){ //Update this to fetch
            if ( response.items ){
                if ( response.items[0].link !== window.location.href ){ //If the top result does not match the current page URL
                    nebula.showSuggestedGCSEPage(response.items[0].title, response.items[0].link); //Show the suggestion
                }
            }
        });
    }
};

Override

To override or disable this JavaScript function, simply redeclare it with the exact same function name.

JavaScript
nebula.tryGCSESearch = function(phrase){
    //Write your own code here, leave it blank, or return false.
}