最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the Google Custom Search (V2) to execute immediately with a pre-loaded search string? - Stack Overflow

programmeradmin3浏览0评论

I've been tasked with adding GCS to a website. After I followed the instructions to create my free GCS (), and pasted the supplied snippet into the appropriate place, the search box & button components render OK and the user is able to enter a search string, run the search and see the results. So far so good.

However, when the components render for the first time I want to be able to pass a pre-entered string into the box and programmatically have the search executed immediately. This bit is not working.

The code I currently have in place is as follows, consisting of the supplied snippet plus some extra code derived from my reading of the Custom Search Element Control API doc () and intended to implement the 'execute immediate':

<div class="content-container">  
    <script type="text/javascript"> 
        (function() { 
            var cx = '(my search id)'; 
            var gcse = document.createElement('script'); 
            gcse.type = 'text/javascript'; 
            gcse.async = true; 
            gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + 
                '//www.google/cse/cse.js?cx=' + cx; 
            var s = document.getElementsByTagName('script')[0]; 
            s.parentNode.insertBefore(gcse, s); 
        })(); 
    </script> 
    <gcse:search> gname="2DSearch"</gcse:search> 
    <script type="text/javascript"> 
        var element = google.search.cse.element.getElement("2DSearch"); 
        element.prefillQuery(primarySearch); 
        element.execute(primarySearch); 
    </script> 
</div> 

primarySearch is the string I want to automatically search on. When the components render, the string 'gname="2DSearch"' appears briefly then disappears again just before the search components appear, then nothing else happens.

There appear to be some similarities here with this question (unanswered):

I have searched the Web in vain for a number of hours for anything else relevant.

Can anybody tell me why it's not working and/or what I need to do?

My apologies, I have done alot of programmming but am virtually illiterate when it comes to HTML & javascript. Thanks Jim

I discovered that the Chrome console is showing the following error: Uncaught ReferenceError: google is not defined

My code now looks like this:

<div class="content-container">
    <script type="text/javascript">
        (function() {
            var cx = '013736134253840884188:fxsx6zqql_y';
            var gcse = document.createElement('script');
            gcse.type = 'text/javascript';
            gcse.async = true;
            gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
                '//www.google/cse/cse.js?cx=' + cx;
            var s = document.getElementsByTagName('script')[0];
            s.parentNode.insertBefore(gcse, s);
        })();
    </script>
</div>

<div class="gcse-search" data-gname="2DSearch"></div>

<div class="content-container">
    <script type="text/javascript" src=""></script>
    <script type="text/javascript">
        var element = google.search.cse.element.getElement("2DSearch");
        element.prefillQuery(primarySearch);
        element.execute(primarySearch);
    </script>
</div>

In the console again I'm now also seeing the following:

XMLHttpRequest cannot load (insert here the jsapi link above that I'm not allowed to post). Origin (insert here the URL for my localhost) is not allowed by Access-Control-Allow-Origin.

There are numerous references to similar errors to this all over the Net, each one slightly different, with solutions proposed referring to JSON, JQUERY, AJAX etc.etc., but nothing that I have found seems directly relevant to what I am trying to do (ie make available to my code the file or library in which 'google' is defined), and nothing that I have tried has worked.

Talk about trying to find your way through a coalmine with a candle... :) Cheers

I've been tasked with adding GCS to a website. After I followed the instructions to create my free GCS (http://www.google.com/cse/sitesearch/create), and pasted the supplied snippet into the appropriate place, the search box & button components render OK and the user is able to enter a search string, run the search and see the results. So far so good.

However, when the components render for the first time I want to be able to pass a pre-entered string into the box and programmatically have the search executed immediately. This bit is not working.

The code I currently have in place is as follows, consisting of the supplied snippet plus some extra code derived from my reading of the Custom Search Element Control API doc (https://developers.google.com/custom-search/docs/element) and intended to implement the 'execute immediate':

<div class="content-container">  
    <script type="text/javascript"> 
        (function() { 
            var cx = '(my search id)'; 
            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> gname="2DSearch"</gcse:search> 
    <script type="text/javascript"> 
        var element = google.search.cse.element.getElement("2DSearch"); 
        element.prefillQuery(primarySearch); 
        element.execute(primarySearch); 
    </script> 
</div> 

primarySearch is the string I want to automatically search on. When the components render, the string 'gname="2DSearch"' appears briefly then disappears again just before the search components appear, then nothing else happens.

There appear to be some similarities here with this question (unanswered): https://stackoverflow.com/questions/15871911/passing-optional-search-parameters-into-google-custom-search-query

I have searched the Web in vain for a number of hours for anything else relevant.

Can anybody tell me why it's not working and/or what I need to do?

My apologies, I have done alot of programmming but am virtually illiterate when it comes to HTML & javascript. Thanks Jim

I discovered that the Chrome console is showing the following error: Uncaught ReferenceError: google is not defined

My code now looks like this:

<div class="content-container">
    <script type="text/javascript">
        (function() {
            var cx = '013736134253840884188:fxsx6zqql_y';
            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>
</div>

<div class="gcse-search" data-gname="2DSearch"></div>

<div class="content-container">
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        var element = google.search.cse.element.getElement("2DSearch");
        element.prefillQuery(primarySearch);
        element.execute(primarySearch);
    </script>
</div>

In the console again I'm now also seeing the following:

XMLHttpRequest cannot load (insert here the jsapi link above that I'm not allowed to post). Origin (insert here the URL for my localhost) is not allowed by Access-Control-Allow-Origin.

There are numerous references to similar errors to this all over the Net, each one slightly different, with solutions proposed referring to JSON, JQUERY, AJAX etc.etc., but nothing that I have found seems directly relevant to what I am trying to do (ie make available to my code the file or library in which 'google' is defined), and nothing that I have tried has worked.

Talk about trying to find your way through a coalmine with a candle... :) Cheers

Share Improve this question edited May 23, 2017 at 11:54 CommunityBot 11 silver badge asked May 31, 2013 at 3:06 user2438826user2438826 611 gold badge1 silver badge4 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 15

I've got it working with the gcse callback option (I also changed my layout in the CSE Control Panel to prevent the default overlay).

<script>
function gcseCallback() {
  if (document.readyState != 'complete')
    return google.setOnLoadCallback(gcseCallback, true);
  google.search.cse.element.render({gname:'gsearch', div:'results', tag:'searchresults-only', attributes:{linkTarget:''}});
  var element = google.search.cse.element.getElement('gsearch');
  element.execute('this is my query');
};
window.__gcse = {
  parsetags: 'explicit',
  callback: gcseCallback
};
(function() {
  var cx = 'YOUR_ENGINE_ID';
  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>

<div id="results"></div>

Can you pass the search term via the URL?

<script>
  (function() {
    var cx = 'YOURID';
    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:searchbox queryParameterName="term"></gcse:searchbox>
<gcse:searchresults></gcse:searchresults>

If you call your "search" page via yourdomain.com/search?term=searchword the search results appear immediately.

<gcse:search gname='abcd'></gcse:search>

And when the page loaded:

google.search.cse.element.getElement('abcd').execute(query);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论