我想用Greasemonkey实现Google自定义搜索API,到目前为止,我的试用主要遇到失败。代码的目标是将自定义搜索框注入现有网站(我正在尝试为MATLAB的文档页面执行此操作,但注入的代码应该可以与任何网站真正配合使用)。我试图通过网上搜索建议的许多方法(主要是关于在Greasemonkey中执行JQuery或Google语言api),并且没有人为自定义搜索api工作...通过Greasemonkey实现Google自定义搜索API
我认为可能存在一些问题变量的作用域,但请让我知道如果任何人有得到它的工作有什么建议?
// Inject the Google API loader script
var script = document.createElement('script');
script.src = 'http://www.google.com/jsapi?callback=gLoaded'; // Call gLoaded() when google api loader is ready.
script.type = "text/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
// Create the <div> tag for the search API to draw the search box
var elmBody = document.getElementsByTagName('Body')[0];
var gSearch = document.createElement('div');
gSearch.id = 'g_search';
elmBody.appendChild(gSearch);
// Let w be the shorthand for unsafeWindow under the Greasemonkey sandbox
var w = unsafeWindow;
// Load the search api using the Google API loader
w.gLoaded= function()
{ w.google.load('search','1', {"callback" : searchLoaded}); } ; // Run searchLoaded() when search API is ready
// Setup the custom search API and draw the search box
searchLoaded = function(){
google = w.google; // unsafeWindow
alert(google); // :debug_1
alert(google.search); // :debug_2
alert(google.search.CurrentLocale); // :debug_3
var mySearch= new google.search.CustomSearchControl('012907575288767046387:tuvzi3yqdkq');
alert(mySearch) // :debug_4
mySearch.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
mySearch.draw('g_search'); // Draw the search box to the <div id='g_search'>
}
- debug_1:返回一个有效的对象
- debug_2:返回一个有效的对象
- debug_3:返回一个有效的s特林( '恩')
- debug_3:返回未定义
- 同样我曾尝试让searchLoaded - > w.searchLoaded并删除了声明(谷歌= w.google),但在这种情况下,所有(1)调试返回undefined。
有趣的是,当我用Javascript shell bookmarklet和重新分配的功能gLoaded()和searchLoaded()非对应Greasemonkey的(无unsafeWindow顾虑)通过命令行,一切只是工作如预期。一个可爱的搜索框显示了它应该在的位置。
而且任何建议,得到它的工作,我不知道......
为什么google.search.CurrentLocale返回的字符串,其中的构造google.search.CustomSearchControl()不能装?
当我将searchLoaded指定为unsafeWindow.searchLoaded(请参阅上面的最后一个注释)时,即使函数默认情况下它们应该位于窗口范围内,该函数也不再可见。但是,当我在javascript shell下为这些函数赋予这些非常相同的值时,一切都奏效了! Greasemonkey以某种方式屏蔽这些变量,即使我已经明确定义了函数在窗口范围内?
我曾尝试用不同的方案(位置劈,@required,google.setOnLoadCallback ...)的变化,但他们没有为我工作。
请让我知道任何...我的意思是任何建议,我跑出来的想法......
谢谢!
谢谢!这个诀窍代码很好用。 但是,请问在CDATA中包含<>和>是什么原因?我尝试着使用和不使用该集合,并且代码以任何方式工作。 – ddwp99 2010-08-07 22:20:27
teorically CDATA应该总是在标签内 这是我的根标签的开始和结束分别 – w35l3y 2010-08-08 01:05:46