在我的页面上呈现搜索结果后,我基本上需要运行一些jQuery代码.我可以使用v1代码:
<div id="cse" style="width: 100%;">Loading</div> <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('search','1',{language : 'en',style : google.loader.themes.V2_DEFAULT}); google.setOnLoadCallback(function() { var customSearchOptions = {}; var orderByOptions = {}; orderByOptions['keys'] = [{label: 'Relevance',key: ''},{label: 'Date',key: 'date'}]; customSearchOptions['enableOrderBy'] = true; customSearchOptions['orderByOptions'] = orderByOptions; var customSearchControl = new google.search.CustomSearchControl( 'zzzzzzzzzzzz',customSearchOptions); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.setAutoComplete(true); customSearchControl.setAutoCompletionId('zzzzzz:zzzzzzz+qptype:3'); options.enableSearchResultsOnly(); customSearchControl.draw('cse',options); function parseParamsFromUrl() { var params = {}; var parts = window.location.search.substr(1).split('\x26'); for (var i = 0; i < parts.length; i++) { var keyValuePair = parts[i].split('='); var key = decodeURIComponent(keyValuePair[0]); params[key] = keyValuePair[1] ? decodeURIComponent(keyValuePair[1].replace(/\+/g,' ')) : keyValuePair[1]; } return params; } var urlParams = parseParamsFromUrl(); var queryParamName = "q"; if (urlParams[queryParamName]) { customSearchControl.execute(urlParams[queryParamName]); } },true); </script>
或者v2代码:
<!-- 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; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse,s); })(); </script>
我有一个函数需要动态设置搜索结果出现的容器高度,所以一旦结果加载我需要调用它,否则我的页面显示不正确.
以下是其v2 API文档的链接:https://developers.google.com/custom-search/docs/element#cse-element和v1:https://developers.google.com/custom-search/docs/js/cselement-reference.我只能在初始化时看到搜索结果呈现回调的任何内容.虽然不支持这样的事情,但似乎很疯狂.
这是我用v2尝试过的:
(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 () { console.log("executed"); SetMainHeight(20); }; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse,s); })();
控制台永远不会输出“已执行”.另外我注意到在我的控制台中我有以下错误:
Unsafe JavaScript attempt to access frame with URL about:blank from frame with URL 07002…s1%2Csr1&rurl=http%3A%2F%2Flocalhost%3A58257%2FSearch%3Fq%3Dtest#slave-1-1. Domains,protocols and ports must match.