Call function after loading google custom search results?

让人想犯罪 __ 提交于 2019-12-04 05:50:25

Unfortunately v2 doesn't have this ability, but in v1 you can use:

.setSearchCompleteCallback(object, method)

You can search for it on this page.

Previous solutions did not work for me, but here's what worked for me:

<script>
  (function() {

    window.__gcse = {
      callback: myCallback
    };

    function myCallback() {
       $('input.gsc-input').keyup(function(e) { if(e.keyCode == 13 || e.which == 13) {  console.log('enter pressed'); }});
      $('input.gsc-search-button').on('click', function(e) { console.log('clicked');});
    }
    var cx = '002806224466286757728:XXXXXXX';
    var gcse = document.createElement('script');
    gcse.type = 'text/javascript';
    gcse.async = false;
    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>

Hope this helps

For v2, for example, try and set an onload handler to the gcse object (script) before inserting it in the DOM.

gcse.onreadystatechange = gcse.onload = function() {
  //execute my code
};

basically you end up with:

<!-- Put the following javascript before the closing </head> tag. -->

<script>
    (function() {
var cx = 'xxxxxxxxx';
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;
gcse.onreadystatechange = gcse.onload = function() {
  //execute your code here
};
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
  })();
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!