Google搜索javascript - 如何获取搜索字词

时间:2014-03-17 13:30:42

标签: javascript jquery google-search

我的网站上有谷歌自定义搜索框(Javascript)。 使用以下代码:

<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>

当用户点击其中一个结果并在目标页面上点击浏览器的后退按钮时,会出现一个空的搜索屏幕。 返回搜索页面时是否可以保留结果页面?

此外,我想从此脚本中检索搜索词,我该怎么做?

提前致谢

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

使用rafael的建议我为我的问题提供了以下解决方案:

<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>