我想要实现的谷歌的定制搜索API与油猴子,到目前为止,我的试验已会晤了大多是失败的。我们的目标码是注定制搜索框入现有的网站(我试图做到这MATLAB的文件网页,但注射代码应该有真正的工作与任何网站)。我已经尝试的方法很多建议通过搜索网上(大多涉及实施备或语言api在油猴子)和没有工作的定制搜索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:返回一个有效的string('en')
  • debug_3:返回不确定
  • 同样,我们试图让searchLoaded->w。searchLoaded和删除的声明(谷歌=w。谷歌),但在这种情况下,所有调试回报不确定的。

有趣的是,当我用的 Javascript壳书签 并重新分配功能gLoaded()和searchLoaded()非油猴子的同行(没有unsafeWindow问题)通过命令线,一切都只是工作为目的。一个可爱的搜索盒显示它应该是。

除了任何建议得到它的工作,我想知道...

  1. 怎么来的。搜索。CurrentLocale返回的有效串,在那里为本构造。搜索。CustomSearchControl()不能弹吗?

  2. 当我分配searchLoaded为unsafeWindow.searchLoaded(见最后注意到以上),谷歌的对象是没有再看到的功能,即使他们应该在窗口的范围默认。然而,当我分配的功能,这些同样的价值观下javascript壳,一切工作!是油猴子的某种屏蔽这些变量即使我必须明确界定的职能在窗口的范围?

我已经试着变化与不同的方案(地点的黑客,@需要。setOnLoadCallback...),但没有人为我工作。

请让我知道的任何...我的意思是任何建议,我的想法...

谢谢!

有帮助吗?

解决方案

基本上...

var script = document.createElement('script'); 
script.type = "text/javascript"; 
script.innerHTML = (<><![CDATA[

// YOUR CODE GOES HERE

]]></>).toString();
document.getElementsByTagName('head')[0].appendChild(script);

写的代码作为一个正常的剧本,不是一个通用的剧本。
我的意思是,除去所有 unsafeWindow 参考文献和相关的东西。
这将使脚本运行在正确的范围。
问题的发生是因为 google.search.CustomSearchControl 使用的变量,如J及K,是不确定的全球机制的范围。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top