amir moradifard
amir moradifard

Reputation: 353

Google Search javascript - How to get the search term

I have google custom search box (Javascript) in my website. with following code:

<script type="text/javascript">
    var searchTerm = "";
    google.load('search', '1', { language: 'en' });

    google.setOnLoadCallback(function() {
        var customSearchControl = new google.search.CustomSearchControl('XXXXX');
        customSearchControl.draw('cse');
        customSearchControl.execute('<%= Request.QueryString["search"] %>');
        customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
        customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
}, true);
</script>

When user clicks on one of the results and on the target page clicks on Browser's back button, an empty search screen appears. Is it possible to keep the results page when getting back to the search page?

Also I would like to retrieve the search term from this script, how can I do that?

Thanks in advance

Upvotes: 0

Views: 4846

Answers (2)

amir moradifard
amir moradifard

Reputation: 353

Using rafael's suggestion I came with following solution for my problem:

<script type="text/javascript">
    var searchTerm = "";
    if (sessionStorage.getItem("googleSearchTerm") != '')
        searchTerm = sessionStorage.getItem("googleSearchTerm");
    runGoogleSearch(searchTerm);

    function runGoogleSearch(searchTerm) {
        google.load('search', '1', { language: 'en' });

        google.setOnLoadCallback(function () {
            var customSearchControl = new google.search.CustomSearchControl('XXXXXX');
            customSearchControl.draw('cse');

            customSearchControl.execute(searchTerm);
        // Set a callback so that whenever a search is started we will call searchStart
        customSearchControl.setSearchStartingCallback(this, searchStart);
        customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
        customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);

    }, true);
    }

    // Whenever a search starts, alert the query.
    function searchStart(searchControl, searcher, query) {
        sessionStorage.setItem("googleSearchTerm", "");
        var content = document.getElementById('content');
        var queryDiv = document.getElementById('query');
        if (!queryDiv) {
            var queryDiv = document.createElement('div');
            queryDiv.id = 'query';
            document.body.appendChild(queryDiv);
        }
        //queryDiv.innerHTML = "User searched for: " + query;
        sessionStorage.setItem("googleSearchTerm", query);

        //alert(sessionStorage.getItem("googleSearchTerm") + " gozo");
    }

</script>

Upvotes: 1

Related Questions