Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@foeken
Last active May 23, 2016 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foeken/e8408759a8be6db3d6f9c1221311daf2 to your computer and use it in GitHub Desktop.
Save foeken/e8408759a8be6db3d6f9c1221311daf2 to your computer and use it in GitHub Desktop.
Crude Google Chrome Ninchanese extension
function getImageUrl(searchTerm, callback, errorCallback) {
var api_key = 'XXX'; // NOTE, the API is limited so you need a personal API key and Custom Search Engine ID
var cx_key = 'XXX'; // SEE: https://github.com/hubot-scripts/hubot-google-images/issues/29#issuecomment-188960728
var searchUrl = 'https://www.googleapis.com/customsearch/v1?q=' + encodeURIComponent(searchTerm) + '&cx='+ cx_key +'&safe=high&searchType=image&key=' + api_key
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
x.responseType = 'json';
x.onload = function() {
var response = x.response;
if (!response || !response.items ||
response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
callback(response.items);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
document.addEventListener('keyup', function(event) {
if( event.code == 'Enter' ) {
var images = document.getElementsByClassName('google-image')
for (var i = images.length - 1; i >= 0; i--) {
images[i].parentNode.removeChild(images[i]);
}
setTimeout(function(){
var answerHanzi = document.getElementById('answer-hanzi').innerText;
var answerEnglish = document.getElementById('answer-definition').innerText
var container = document.getElementsByClassName('english-word')[0];
getImageUrl(answerHanzi, function(items) {
for (var i = 4; i >= 0; i--) {
var image = document.createElement("img");
image.className = 'google-image';
image.width = 150;
image.src = items[i].image.thumbnailLink;
container.appendChild(image);
}
}, function(errorMessage) { console.log(errorMessage) });
}, 200);
}
});
{
"manifest_version": 2,
"name": "Ninchanese Images",
"description": "This extension shows a Google image search for each word.",
"version": "1.0",
"content_scripts": [
{
"matches": ["https://app.ninchanese.com/*"],
"js": ["content.js"]
}
],
"browser_action": {
"default_title": "Show Google images for guessed words!"
},
"permissions": [
"https://ajax.googleapis.com/",
"https://www.googleapis.com/"
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment