execute google image search several times in a page - javascript

I want to write a web page which can generate images get from google search dynamically.
The search terms for these images are different, so I need to execute google search several times, while I found it is very hard.
I try these code modified from the source code google provided, but it could only execute the search one time:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
var keyword="sexy";
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src=result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
//clear search
imageSearch.clearResults();
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
imageSearch.execute(keyword);
}
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<button value="hi" onClick="hi">hi</button>
<div id="content">Loading...</div>
</body>
</html>
The program can only execute the search in OnLoad method. Actually, I tried to call google.setOnLoadCallback(OnLoad) multiple times by put it into hi() function, but it didn't work.
Hope someone can help me to solve these problem..

change <button value="hi" onClick="hi">hi</button> to
<button value="hi" onClick="hi()">hi</button>

The hi function doesn't make a lot of sense to me:
function hi(){
keyword="usa";
alert('hi');
google.setOnLoadCallback(OnLoad);
imageSearch.execute(keyword);
}
Because the onLoadCallbak has already been set, and a search executed in OnLoad. This is called when the search library has loaded. Which only happens once, at some point after the page has loaded.
What you need to do in hi is the same thing you're doing in OnLoad:
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// set a DIFFERENT callback (if different handling require)
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
// set "keyword" to what your next search should be for
imageSearch.execute(keyword);

Related

How to access an iframe from chrome extension?

How can I get my extension to work on all frames like adblock does?
I tried adding "all_frames" : true to my manifest file but it didn't work.
I tried to use this code to get the text with specific ids:
var theId = "starts with something";
var myArray = [];
$('[id^="theId"]').each(function(i, obj) {
myArray.push($(this).text());
});
$.unique(myArray);
console.log(myArray);
but it says my array is empty. When I inspect element on the page, I see a "top" layer, and a "target content" layer. The code only works when I execute it in the console on the "target content" layer. Can I use this code in a content script, or do I need to use background.js somehow?
Continued from SO44122853
I see you figured out that the content was loaded in an iframe. So I have a working demo here PLUNKER, the snippet is here just in case the plunker goes down.
Details are commented in PLUNKER
Demo
Not functional due to the need to run 2 separate pages
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<style></style>
</head>
<body>
<!--iframe is same as the one on the site, with the exception
of the src-->
<iframe id="ptifrmtgtframe" name="TargetContent" title="Main Content" frameborder="0" scrolling="auto" width='90%' src="tables.html"></iframe>
<!--The data is displayed as a one string-->
<output id='display'></output>
<script>
// Reference the iframe
var iFID = document.getElementById("ptifrmtgtframe");
// Register the load event on iframe
iFID.onload = function(e) {
// Callback is extractText function
return extractText('#ptifrmtgtframe', '#display', '.PSLONGEDITBOX');
}
/* Pass iframe and display as a single selector
|| Pass targets as a multiple selector
*/
function extractText(iframe, display, targets) {
var iArray = [];
var iFrame = document.querySelector(iframe);
var iView = document.querySelector(display);
var iNode = "";
/* .contentWindow is property that refers to content
|| that is in an iframe. This is the heart of the
|| demo.
*/
var iContent = iFrame.contentDocument || iFrame.contentWindow.document;
var iTarget = iContent.querySelectorAll(targets);
/* .map() will call a function on each element
|| and return a new array as well.
*/
Array.from(iTarget).map(function(node, idx) {
iNode = node.textContent;
iView.textContent += iNode;
iArray.push(iNode);
return iArray;
});
console.log(iArray);
}
</script>
</body>
I think your script may be executing before the DOM loads, try putting your function inside:
document.addEventListener('DOMContentLoaded', function() {
});
EDIT
That event seems to do nothing in content scripts, I think that is because they are already loading after DOM is loaded, and never fires.
However this seems to fire but not sure why:
$(function(){
//something
});
This needs jQuery injected aswell

Cordova SQLite plugin only works on first call

I have a cordova app with two pages, the first has a search field and the second displays the results of the first.
The displayResults function
function displayResults(){
var query = localStorage.getItem('search');
var db = window.sqlitePlugin.openDatabase({name:"Store-DB", location: 1});
queryDB(db,query);
}
function queryDB(db,query){
db.transaction(function(tx) {
var queryList = query.split(" ");
var sqlText = "SELECT * FROM DB WHERE item LIKE '%"+queryList[0]+"%'";
for (i = 1; i < queryList.length; i++) {
sqlText += " OR item LIKE '%"+queryList[i]+"%'";
}
tx.executeSql(sqlText, [], querySuccess);
}
);
}
function querySuccess(tx,results) {
var i;
var len = results.rows.length;
//Iterate through the results
for (i = 0; i < len; i++) {
console.log(row);
//Get the current row
var row = results.rows.item(i);
var div = document.createElement("div");
div.style.background = "gray";
div.style.color = "white";
div.innerHTML = row;
document.body.appendChild(div);
}
alert("Finished");
}
Here is the code for the second page:
<link rel="stylesheet" type="text/css" href="css/default.css">
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="js/zepto.js" type="text/javascript"></script>
<script src="plugins/com.brodysoft.sqlitePlugin/www/SQLitePlugin.js" type="text/javascript"></script>
<script src="js/code.js" type="text/javascript"></script>
<script type="text/javascript">
function onLoad(){
document.addEventListener("deviceready", onDeviceReady(), false);
}
function onDeviceReady(){
displayResults();
}
</script>
</head>
<body onload="onLoad()">
<div id="taskbar">
Home
<a id="username" class="toolbar_item" style="float:right;" href="#"></a>
</div>
The first time you load this page displayResults works just fine, but if you click the link back to the main page and load the second page again the console prints the error ReferenceError: no "undefined" has no property "openDatabase" in other words, the SQLite plugin isn't loading. But, if I make displayResults fire on a button press instead of onload it works every time. What is the explanation for this peculiar behavior?
It seems that sometimes deviceready-event is either not fired at all or fired too early when there are more event handlers of different libraries in place. The second problem caused that the brodysoft-plugin is not loaded properly and assign to the window-object as window.sqlitePlugin property because one event handler dispatched deviceready-event too early. It turned out setTimeout was the answer as it had been here
You can use the onpageshow event for example
$('#idofyourpage').bind("onpageshow",function(){
//Do something
});

How to run and display processing code (currently in part of the document.body) in an html canvas?

NOTE: I know I can import .pde files but I need to run code on screen so I will not be using this.
My three following attempts failed. I do not know which one was closer to achieving and I do not prefer one as long as it produces desired result. Appreciate the help by helping me get any of the attempts working/suggesting a new one.
1ST ATTEMPT) - use getText function written below but then some text that is not code can be found in the resulting jscode variable and thus the processing instance does not work.
function getText(n) {
var s = [];
function getStrings(n, s) {
var m;
if (n.nodeType == 3) { // TEXT_NODE
s.push(n.data);
}
else if (n.nodeType == 1) { // ELEMENT_NODE
for (m = n.firstChild; null != m; m = m.nextSibling) {
getStrings(m, s);
}
}
}
getStrings(n, s);
var result = s.join(" ");
return result;
}
var processingCode = getText(document.body)
processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = document.getElementById("mysketch");
var processingInstance = new Processing(canvas, jsCode);
....
<span class="sketch">
<canvas id="mysketch"></canvas>
</span>
2ND ATTEMPT) Same as above but added a tag with id="all_processing_code" but couldn't figure out how to get the text within anyway. This did not work:
var processingCode = getText(document.getElementbyId(all_processing_code));
3RD ATTEMPT) Removed getText and tried to use JQuery text() to isolate the code. Was having trouble mixing JS and Jquery though. Tried different stuff and none worked. What would be appropriate way to mix it in? What script type should I use? This was confusing.
<script type="text/jquery">
var processingCode = $('#all_processing_code').text();
//processingCode.replace(/<[^>]+>¦&[^;]+;/g,'').replace(/ {2,}/g,' ');
var jsCode = $.Processing.compile(processingCode).sourceCode;
alert(jsCode);
var canvas = $(#'mysketch');
var processingInstance = new $.Processing($('canvas'), $('jsCode'));
}
</script>
First, check if your processing code is wrapped by an html element (like a div or something else) with an id. If it isn't, please do it!
For exemple:
<div id="mycode">
void setup() {
background(0);
}
</div>
After this, check if you have the getProcessingSketchId() function declared in your code. Processing IDE in JavaScript mode already exports html files with that function. If there isn't, please declare it inside your <head>:
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
You can include JQuery from google api including this line in your html before you use JQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
</script>
Assuming that you want to run your processing code when the page just has loaded, just append this code after the getProcessingSketchId() declaration.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
You can create this code inside any other <script type="text/javascript">.
At the end, you will have something like this:
<html>
<head>
<!-- Your title, meta tags, stylesheet and all other stuff here -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
// convenience function to get the id attribute of generated sketch html element
function getProcessingSketchId () { return 'yourcanvasid'; }
$(document).ready(function() {
new Processing(getProcessingSketchId(), $('#mycode').html());
});
</script>
</head>
<body>
<div id="mycode">
void setup() {
background(0);
}
</div>
</body>
</html>

Google Feed API

I'm having trouble getting Google's load feed to work. Example is supposed to be at www.eslangel.com
I put this code in the header
<script type="text/javascript"
src="https://www.google.com/jsapi?key=ABQIAAAAO2BkRpn5CP_ch4HtkkOcrhQRKBUhIk5KoCHRT6uc9AuUs_-7BhRyoJdFuwAeeqxoUV6mD6bRDZLjSw">
</script>
And then, just to test, I copied and pasted their sample code using a Digg feed into the body of my blog, but there's no result of any kind.
Does anyone have any idea what I might be doing wrong?
/*
* How to load a feed via the Feeds API.
*/
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
// Grab the container we will put the results into
var container = document.getElementById("content");
container.innerHTML = '';
// Loop through the feeds, putting the titles onto the page.
// Check out the result object for a list of properties returned in each entry.
// http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
}
function OnLoad() {
// Create a feed instance that will grab Digg's feed.
var feed = new google.feeds.Feed("http://www.digg.com/rss/index.xml");
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(OnLoad);​
Well, did you also create a container for the feed? :-)
Try placing
<div id="content"></div>
before the feed loading script.

Javascript Onclicks not working?

I have a jQuery application which finds a specific div, and edit's its inner HTML. As it does this, it adds several divs with onclicks designed to call a function in my JS.
For some strange reason, clicking on these never works if I have a function defined in my code set to activate. However, it works fine when calling "alert("Testing");".
I am quite bewildered at this as I have in the past been able to make code-generated onclicks work just fine. The only thing new here is jQuery.
Code:
function button(votefor)
{
var oc = 'function(){activate();}'
return '<span onclick=\''+oc+'\' class="geoBut">'+ votefor +'</span>';
}
Elsewhere in code:
var buttons = '';
for (var i = 2; i < strs.length; i++)
{
buttons += button(strs[i]);
}
var output = '<div name="pwermess" class="geoCon"><div class="geoBox" style=""><br/><div>'+text+'</div><br/><div>'+buttons+'</div><br/><div name="percentages"></div</div><br/></div>';
$(obj).html(output);
Elsewhere:
function activate()
{
alert("Testing");
}
You may want to take a look at jQuery.live(eventType, eventHandler), which binds an event handler to objects (matching a selector) whenever they are created, e.g.:
$(".somebtn").live("click", myClickHandler);
Follows a dummy example, may be this can help you.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
<script src="http://cdn.jquerytools.org/1.2.5/jquery.tools.min.js"></script>
<script type="text/javascript">
$(function() {
$('.go-right').click(function(){
c="Hello world";
$("#output").html(c);
});
});
</script>
</head>
<body >
<div id="output"></div>
<a class="go-right">RIGHT</a>
</body>
</html>
Change this:
var oc = 'function(){activate();}'
To be this instead:
var oc = 'activate();'

Categories

Resources