Is there a working sample of the Google custom search rest API? - google-custom-search

I need to create a screen which automates Google search.
I know JavaScript and I'm trying to get GSE works.
I have a search engine and an API key.
The problem is Google's documentation is cyclic i.e. pages point to each other.
There is no working sample from where I can start my research.
Please help if you know of a working sample.
The documents I have read are:
cselement-devguide
introduction

I know this is an old question, but here is what I did to make the API results formatted like the Google Site Search used to give since they are ending the paid accounts and will have ads now. The API way has an option to pay still for over 100 searches per day, so going with that but had to format the results still, and used the existing one to build the css to do similar styling also.
Search form going to this page is just a simple:
<form action="search-results.htm" id="cse-search-box">
<div>
<input class="" name="q" type="text">
<input class="" type="submit">
</div>
</form>
and then the search results page:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>JSON/Atom Custom Search API Example</title>
<!--<link href="default.css" rel="stylesheet" type="text/css">-->
<link href="google.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="gsc-result-info" id="resInfo-0"></div>
<hr/>
<div id="googleContent"></div>
<script>
//Handler for response from google.
function hndlr(response) {
if (response.items == null) {
//Sometimes there is a strange thing with the results where it says there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
//So if we get to the invalid one, send them back a page.
window.location.replace("searchresults.htm?start=" + (start - 10) + "&q=" + query);
return;
}
//Search results load time
document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
//Clear the div first, CMS is inserting a space for some reason.
document.getElementById("googleContent").innerHTML = "";
//Loop through each item in search results
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
var content = "";
content += "<div class='gs-webResult gs-result'>" +
"<table class='gsc-table-result'><tbody><tr>";
//Thumbnail image
if (item.pagemap.cse_thumbnail != null)
content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
"<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
//Link
content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
//File format for PDF, etc.
if (item.fileFormat != null)
content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
//description text and URL text.
content += item.htmlSnippet.replace('<br>','') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl +"</div>" +
"<br/></td></tr></tbody></table></div>";
document.getElementById("googleContent").innerHTML += content;
}
//Page Controls
var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
console.log(totalPages);
var currentPage = Math.floor(start / 10 + 1);
console.log(currentPage);
var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
//Page change controls, 10 max.
for (var x = 1; x <= totalPages && x<=10; x++) {
pageControls += "<div class='gsc-cursor-page";
if (x === currentPage)
pageControls += " gsc-cursor-current-page";
var pageLinkStart = x * 10 - 9;
pageControls+="'><a href='search-results.htm?start="+pageLinkStart+"&q="+query+"'>"+x+"</a></div>";
}
pageControls += "</div></div></div>";
document.getElementById("googleContent").innerHTML += pageControls;
}
//Get search text from query string.
var query = document.URL.substr(document.URL.indexOf("q=") + 2);
var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
if (start === "1&" || document.URL.indexOf("start=") === -1)
start = 1;
//Load the script src dynamically to load script with query to call.
// DOM: Create the script element
var jsElm = document.createElement("script");
// set the type attribute
jsElm.type = "application/javascript";
// make the script element load file
jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourApikeyhere&cx=yoursearchengineidhere&start="+start+"&q=" +query +"&callback=hndlr";
// finally insert the element to the body element in order to load the script
document.body.appendChild(jsElm);
</script>
</body>
</html>

Related

Using document.getElementsByClassName in Testcafe

I have a menu that always has the same structure, but the IDs can change from one installation to another. the only thing that stays the same is the heading (in my case "Plugins"). I call the document.getElementsByClassName function with a Selector inside my test:
var slides = Selector(() =>{
return document.getElementsByClassName("c-p-header-text");
});
Every heading of an menu element has the c-p-header-text class. Here is what a menu heading element looks like:
<div id="ext-comp-1002" class="c-p c-tree c-p-collapsed" style="width: auto;">
<div class="c-p-header c-unselectable c-accordion-hd" id="ext-gen135" style="cursor: pointer;">
<div class="c-tool c-tool-toggle" id="ext-gen140"> </div>
<img src="/backEnd/images/s.gif" class="c-p-inline-icon order"><span class="c-p-header-text" id="ext-gen150">Plugins</span>
</div>
It would be easy to use await t.click("#ext-gen150") but it is not safe that it is always this id.
here is what i tried:
await t
.click('#sites__db');
var slides = Selector(() =>{
return document.getElementsByClassName("c-p-header-text");
});
console.log("[DEBUG]" + slides);
console.log("[DEBUG] found " + slides.length + " elements");
for(var i = 0; i < slides.length; i++)
{
var txtOfCurrElem = slides.item(i).innerText;
console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
Running this test give me the following output:
[DEBUG]function __$$clientFunction$$() {
var testRun = builder.getBoundTestRun() || _testRunTracker2.default.resolveContextTestRun();
var callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
var args = [];
// OPTIMIZATION: don't leak `arguments` object.
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}return builder._executeCommand(args, testRun, callsite);
}
[DEBUG] found 0 elements
The plan is to find the element (with the heading "Plugins") and then click on it when the test continuous.
You don't have to use document.getElementsByClassName in this case. You can just use CSS class selector instead:
var slides = Selector('.c-p-header-text');
You should use the count property when dealing with an array of Selectors. docs. Also, element properties, like exists, count, and DOM node state properties are Promisified, so when you use them not in t.expect, you should use the await keyword:
var count = await slides.length;
console.log("[DEBUG] found " + count + " elements");
for(var i = 0; i < count; i++)
{
var txtOfCurrElem = await slides.nth(i).innerText;
console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
I found a simple answer to my question. I use the .withText option to click on the Plugins element:
.click(Selector('span').withText("Plugins"))
Since this name is also unique, it is always the correct element that gets clicked. I do not know if it would have worked with the solution from #AndreyBelym if my site is not an extJS web application.

Page Control while HTML to PDF Conversion using Select PDF

I am trying to convert large HTML file to PDF. but just want to set first page and following page number.
I have used following code
converter = New HtmlToPdf()
Dim file As String = "C:\TEMP\Document5.pdf"
converter.Options.PdfPageSize = PdfPageSize.A4
converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait
converter.Options.MarginTop = 20
converter.Options.MarginBottom = 20
converter.Options.MarginLeft = 10
converter.Options.MarginRight = 10
converter.Options.DisplayFooter = True
Dim doc As PdfDocument = converter.ConvertHtmlString(htmlString)
converter.Footer.TotalPagesOffset =2
converter.Footer.FirstPageNumber = 2
doc.Save(file)
' close pdf document
doc.Close()
but this part not working,
converter.Footer.TotalPagesOffset =2
converter.Footer.FirstPageNumber = 2
and Is there any what to know total pages?
Here's how I handle my page numbering using SelectPDF and ASP.NET MVC Razor.
for (int x = 0; x < PDF.Pages.Count; x++) {
if (x > 0 && x != PDF.Pages.Count - 1) { // will not number first/last page
PdfPage page = PDF.Pages[x];
PdfTemplate customFooter = PDF.AddTemplate(page.PageSize.Width, 33f);
page.DisplayFooter = true;
PdfHtmlElement customHtml = new PdfHtmlElement(domain + "/template/_pagenumber?pageNum=" + x.ToString() + "&totalPages=" + PDF.Pages.Count.ToString());
customFooter.Add(customHtml);
page.CustomFooter = customFooter;
}
}
And here's what my _pagenumber.cshtml file looks like...
<div style="margin-right:48px;margin-left:48px;height:46px;position:relative;top:-4px;z-index:999;">
<div class="row">
<div class="col-xs-6">
<small>Company info goes here</small>
</div>
<div class="col-xs-6 text-right">
<small><strong>Page #(Request.QueryString["pageNum"]) of #(Request.QueryString["totalPages"])</strong></small>
</div>
</div>
</div>

PhantomJS PDF page break

I create a PDF report with header generated automatically by phantomjs. In the report I have a long div which contains text, blank lines, simple data tables etc.
Since I believe phantomjs might have problem with the page break, I calculate the page break manually, break up the long div into multiple divs with page break at the end of each div.
Here is my calculation in the jQuery(document).ready()
//pagination the Notes pages
if (encData.pnotes && encData.pnotes.length > 0) {
pageCnt++;
var $notes = jQuery('<div id="pageNotes" class="notes" style="width:100%;margin-top:100px;border:1px solid red">' +
pNotesString + '</div>');
$body.append($notes);
var height = 0;
var children = $notes.children();
var p = children.slice(0);
var pages = [];
var counter = 0;
for (var i = 0; i < children.length; i++) {
if (height + children[i].offsetHeight < 1350)
height += children[i].offsetHeight;
else {
pages.push([counter, i]);
height = 0;
counter = i;
}
}
pages.push([counter, children.length]);
for (var i = 0; i < pages.length; i++) {
//first notes page
if (i == 0) {
$notes.children().slice(pages[i][1]).remove();
$notes.after('<div style="border:1px solid black;height:1px"></div><div id="pageNotesBreak" style="page-break-after:always"> </div>');
}
else {
pageCnt++;
var $new = jQuery('<div id="page' + pageCnt + '" class="notes" style="width:100%;margin-top:100px;border:1px solid blue"></div>');
$new.append(p.slice(pages[i][0], pages[i][1]));
$body.append($new);
$body.append('<div style="border:1px solid black;height:1px"></div><div id="pageBreak' + pageCnt + '" style="page-break-after:always"> </div>');
}
}
The "<div style='border:1px solid black;height:1px'>" is just a silly marker to find where my page breaks are on the PDF.
1350px in the estimated height of objects where the page break should be created when I traverse all the children of the long div.
In Chrome, I see that I have a total of 5 pages.
But when it is rendered in PDF, the number of pages goes up to 6 or 7 depending the size of the font, the line height, etc.
Here is the image of the pages
Does anyone know the cause of the problem? And how to solve it in general.

Alert does not stay open

When I execute an alert, the alert shows and disappears too quickly. I want it to stay open. What is problem?
After I submit form:
newAlert('success', 'saved');
function newAlert(type, message) {
$('#alert-area').append($("<div class='alert " + type + "'><p> "
+ message + "
</p></div>"));
}
<div id="alert-area"></div>
Im not good at jquery, so I try your question with js, its ok. The "alert-area" div did not disappear. This is my code :
<html>
<head></head>
<body>
<div id="alert-area"></div>
<script type="text/javascript">
window.onload = newAlert('success', 'saved');
function newAlert(type, message) {
document.getElementById('alert-area').innerHTML="<div class='alert " + type + "'><p> " + message + "</p></div>";
}
</script>
</body>
<html>

Get the hostname with action script 2

I am creating some campaign swf banners and I don't use action script very often so any help from the experts would be great thanks.
I am supplying my banners on my website as resource downloads. And tutorials of how to embed the swf which has some javascript flashvars.
These flash variable is then concatenated into a google campaign link to change the utm_source.
This is my javascript...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
flashvars.campaignSource = window.location.hostname;
var params = {};
params.loop = "true";
params.quality = "best";
params.wmode = "opaque";
params.swliveconnect = "true";
params.allowscriptaccess = "always";
var attributes = {};
swfobject.embedSWF("banner.swf", "banner_mpu", "300", "250", "9.0.0", false, flashvars, params, attributes);
</script>
and my html...
<div id="banner_mpu">
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
</div>
So the above js works great, however, not everyone will use my tutorial code and will probably use there own methods to embed the swf banner on their site.
So I need some back up action script 2 to get the current hostname into a action script variable
This is my action script which I have so far on my button (swf)...
on(release) {
function GetTheHostname() {
var RootFullUrl = _root._url;
txtFullUrl.text = RootFullUrl;
var lastSlashIndex:Number = RootFullUrl.lastIndexOf("/");
var DriveIndex:Number = RootFullUrl.indexOf("|");
if (DriveIndex>=0) {
baseUrl = RootFullUrl.substring(0, DriveIndex);
baseUrl += ":";
} else {
baseUrl = "";
}
baseUrl += RootFullUrl.substring(DriveIndex+1, lastSlashIndex+1);
txtBaseUrl.text = baseUrl;
return baseUrl;
}
var campaignSourceAS2:String= GetTheHostname();
if ( _root.campaignSource == undefined ) {
getURL("http://www.mysite.co.uk/?utm_source=" + campaignSourceAS2 + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");
} else {
getURL("http://www.mysite.co.uk/?utm_source=" + _root.campaignSource + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");
}
}
The problem with my action script is that it returns the full current URL.
Can any one please help me adapt the GetTheHostname function to get the host name instead of the baseURL
Thanks in advance
In that case, I guess it would be as easy as stripping the http:// from the url and then get all that's left to the first /
A one-liner to go from 'http://www.example.com/category/actionscript' to 'www.example.com' would be
var baseURL:String = _root._url.split("http://").join("").split("/")[0];
and to replace your full method
getURL("http://www.mysite.co.uk/?utm_source=" + (_root.campaignSource || _root._url.split("http://").join("").split("/")[0]) + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");