Implementing the Google UI API through Greasemonkey

I want to implement the Google Custom Search API using Greasemonkey, and so far my trials have come up mostly with bugs. The purpose of the code is to introduce a custom search box into an existing site (I'm trying to do this for MATLAB documentation pages, but the injection code should really work with any site). I tried using many of the methods offered by web searches (mainly related to the implementation of jQuery or the Google API api in Greasemonkey) and no one worked for a custom api search ...

I think there might be some kind of problem with the variable scope, but please let me know if anyone has any suggestions for working with it.

// 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: returns a valid object
  • debug_2:
  • debug_3: ('en')
  • debug_3: undefined
  • , searchLoaded → w.searchLoaded (google = w.google), undefined.

, Javascript gLoaded() searchLoaded() -Greasemonkey (Window ) , . , .

- , , ...

  • google.search.CurrentLocale , google.search.CustomSearchControl()?

  • searchLoaded unsafeWindow.searchLoaded(. ), google , . , javascript, ! Greasemonkey - , , ?

(hack, @required, google.setOnLoadCallback...), .

, ... , ...

!

+3
1

...

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

// YOUR CODE GOES HERE

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

script, GM script.
, unsafeWindow .
script .
- , google.search.CustomSearchControl , J K, undefined GM.

+3

Source: https://habr.com/ru/post/1758104/


All Articles