2015-03-30 66 views
0

我正在使用他的網站上免費的谷歌自定義搜索的朋友。他有一個小部件,它搜索網絡成員博客列表(在各種平臺上),然後返回結果。我想知道是否有一種方法來添加一個按鈕 - 使用jQuery或JavaScript - 它將執行一個隨機詞的搜索。從谷歌自定義搜索返回隨機帖子

This SO article似乎是合理的,通過創建第二個動作按鈕,添加一個熱門標籤或主題數組中的隨機詞,但似乎應該有更直接的東西。

關鍵是人們可以去搜索引擎,點擊「隨機郵政」有一些文章返回的靈感等。從我可以告訴,谷歌搜索API(現已棄用)可以做到這一點相當容易。我似乎無法找到任何人嘗試使用自定義搜索做類似的事情,我會欣賞一個小方向。謝謝。

回答

0

該解決方案在Custom Search API包括:
使用返回的元素對象的​​方法,通過google.search.cse.element.getElement()

var queries = ['custom search', 'random', 'google', 'Brian Bennett']; 
 
document.querySelector('button').addEventListener('click', function() { 
 
     var cseElement = google.search.cse.element.getElement('standard0'); 
 
     var rand = Math.floor(Math.random() * queries.length); 
 
     cseElement.execute(queries[rand]); 
 
     }, false);
<script> 
 
    (function() { 
 
    var cx = '011833858776650720395:4l5dii3zv2w'; 
 
    var gcse = document.createElement('script'); 
 
    gcse.type = 'text/javascript'; 
 
    gcse.async = true; 
 
    gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + 
 
     '//www.google.com/cse/cse.js?cx=' + cx; 
 
    var s = document.getElementsByTagName('script')[0]; 
 
    s.parentNode.insertBefore(gcse, s); 
 
    })(); 
 
</script> 
 
<gcse:search></gcse:search> 
 
<button>Random search</button>

+0

因爲我學習,我沒有看到一個重大的在您的實施和我在下面發佈的不同之處。是否更好 - 一般來說 - 使用API​​方法來運行搜索?換句話說,爲什麼這個答案比我提出的解決方案更好? – Brian 2015-03-31 13:24:28

+0

因爲這是Google推薦的方式,因爲它不會改變您的實際位置,因爲如果有一天,Google決定改變它處理這些請求的方式(例如,如果它們阻止直接訪問您要轉移的頁面你的用戶),你將不得不重新編寫你的代碼。也就是說,選擇哪種解決方案最適合您的需求取決於您。 – Kaiido 2015-03-31 15:18:35

0

這不是很優雅,但我最終解決了這個問題,方法是設置一組搜索條件,然後用自定義搜索按鈕填充Google自定義搜索字段。

使用this SO post作爲模型,除了自定義搜索HTML之外,還使用新按鈕設置了我的HTML。

<form id="cse-search-box" action="http://google.com/cse"> 
    <input type="hidden" name="cx" value="partner-pub-2789521296837340:9402765321" /> 
    <input type="hidden" name="ie" value="UTF-8" /> 
    <input type="text" name="q" size="31" /> 
    <input type="submit" name="sa" value="Search" /> 
    <!-- This is the new button - the "random" ID allows it to be targeted separately. --> 
    <input id="random" type="submit" name="random" value="Random" /> 
</form> 

現在的形式成立,我們需要添加的可能的搜索項的數組以及函數隨機選擇從陣列中的一個話題。

// With input selected, do this on click 
$("input#random").on('click', function() { 

    // The array of possible search terms. 
    var myArray = ['animals','dogs','cats', 'emu','fish','snakes', 'panda bears','meerkats','spiders','birds']; 

    // Choose a term randomly 
    var rand = myArray[Math.floor(Math.random() * myArray.length)]; 

    // Write them term in the search box and then submit the search 
    var input = $("input[name='q']"); 
    input.val(input.val() + ' ' + rand); 

    $("form#cse-search-box").submit(); 
}); 

顯然,數組越大,隨機性越好。我想改善的一件事是通過閱讀這些正在搜索的博客和網站的RSS提要以編程方式創建數組。儘管如此,現在仍然有效。