Search code examples
javascripthtmlspring-bootthymeleafgoogle-custom-search

Google Custom Search Engine - Is it possible to make a script where I only get the results of a search word not written in the search bar?


I have a Spring Boot project with Thymeleaf where I try to search with an already given input that can be fetched with Thymeleaf, such that when they click a button the search word(s) from that input gets used in a gcse search result. Also is it possible that on the result page, when you click a link it doesn't open in a new window, but the same?

<div class="gcse-searchbox-only">
    <script>
        (function() {
            var cx = '012899561505164599335:sxqdbjuqaxm';
            var gcse = document.createElement('script');
            gcse.type = 'text/javascript';
            gcse.async = true;
            gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(gcse, s);
        })();
    </script>
</div>

This is a gcse script that is used by Capec, here I want to add such that the search takes a string value as search word and not use the input search bar for this. I know that I can change the gcse-searchbox-only to gcse-searchresults-only to remove the search bar, but how do I then search with a search word?

EDIT: Found the solution for my problems (Posted below as an answer).


Solution

  • I found the solution for the auto submit with my search. Found under, from: https://developers.google.com/custom-search/docs/tutorial/implementingsearchbox

    To implement a stand-alone search results page, paste the results code snippet into your results page:

    <script async src="https://cse.google.com/cse.js?cx=YOUR_ENGINE_ID"></script>
    <div class="gcse-searchresults-only"></div>
    

    Now you can trigger search results on this page by passing a "q" argument in the url:

    https://my-results-page-url.com/?q=myQuery Note the q=myQuery param in the address bar - this is how the element knows what query results to display.

    For the clicking of search result link, this is how you stay within the same window: https://blog.expertrec.com/google-custom-search-open-in-same-window/ I used method 2, where you add _parent to link target in the GCSE settings.