Custom Google Search In Webpage [duplicate] - html

This question already has answers here:
How can I add an integrated Google search to my website?
(6 answers)
Closed 9 years ago.
I was wondering how i can make my own custom google search.
Can i do something like this :
<form action="http://www.google.com/search=q?+text input" method="get">
<input type="search">
<input type="submit">
</form>

Try custom search api provided by Google for this. Though it is not pure HTML.
The following code demonstrates how to render a search box, together with search results, in a div, using the explicit parsetag and function callback:
<div id="test"></div>
<script>
var myCallback = function() {
if (document.readyState == 'complete') {
// Document is ready when CSE element is initialized.
// Render an element with both search box and search results in div with id 'test'.
google.search.cse.element.render(
{
div: "test",
tag: 'search'
});
} else {
// Document is not ready yet, when CSE element is initialized.
google.setOnLoadCallback(function() {
// Render an element with both search box and search results in div with id 'test'.
google.search.cse.element.render(
{
div: "test",
tag: 'search'
});
}, true);
}
};
// Insert it before the CSE code snippet so that cse.js can take the script
// parameters, like parsetags, callbacks.
window.__gcse = {
parsetags: 'explicit',
callback: myCallback
};
(function() {
var cx = '123:456'; // Insert your own Custom Search engine ID here
var gcse = document.createElement('script'); gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gcse, s);
})();
</script>
This is the tutorial link.

Please refer the following steps to create google custom search
1.First u have Sign up to Google Account
2.go to this url https://www.google.com/cse/create/new
3.Then specify the website URL (where to search )
4.click on Create button
5.in the next page there are 3 buttons available from that Click on "Get Code" Button.
6.after clicking on that, its generate the code. Copy that code and paste in your webpage.

Google have their own walkthrough,
https://www.google.com/cse/

Related

HTML website url contains /#[object Object] when navigating

I have a website and it contains the following code:
<li class="scroll-to-section">Services</li>
and the appropriate section:
<section class="section" id="services">
...
</section>
When I press the li element, the page scrolls to the services section as expected however, the url is appended with /#[object Object] instead of /services.
Here's an image:
Any idea about what the issue may be?
EDIT: Sorry, forgot to add the javascript: The issue was the new_target variable. I had to change it to new_target as it was also target before and that fixed the issue!
$(document).ready(function() {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on("click", function(e) {
e.preventDefault();
$(document).off("scroll");
$("a").each(function() {
$(this).removeClass("active");
});
$(this).addClass("active");
var target = this.hash,
menu = target;
var new_target = $(this.hash);
$("html, body")
.stop()
.animate(
{
scrollTop: new_target.offset().top - 79
},
500,
"swing",
function() {
window.location.hash = target;
$(document).on("scroll", onScroll);
}
);
});
});
The question doesn't allows us to examine the problem in big detail but here is -at a glance- what is going on:
You are trying to assign an object to a place where only strings are valid.
Take a look at the following example:
function changeText() {
document.getElementById("input").value = "hello"
}
function changeTextWrong() {
document.getElementById("input").value = {link: "hello"}
}
<input id="input" value="sample text"/>
<button onclick="changeText()">change text (OK)</button>
<button onclick="changeTextWrong()">change text (WRONG)</button>
When the input text (equivalent to the url bar) receives the text "hello" it works because "hello" is a text. However when the input text receives an object, this object is then converted into a string. Any object converted into a string is equivalent to "[object Object]".
Solution? Instead of doing window.location.hash = object you very likely need to do something like window.location.hash = object.hash, or window.location.hash = object.WhAtEvEr depending on the object's actual content.
i think you tried to simplify the question without presenting us the complete or relevant code.
From your example, if you only do that it should work but i have a feeling that your code is doing more than that.
#adelriosantiago was right in pointing out that you might return an object instead of the expected string.

How to create href link inside controller in Angularjs?

I am showing a flash error message if a mobile number is not validated.
Flash message as "Mobile number not validated. click here to validate".
But I want to display the same error message with "click here" as the hyper link which will redirect me to the top of the page.
if (res.json.response.mobilevalidated == false) {
FlashService.Error("Mobile number not validated." + ( click here ) +" to validate", false);
$scope.disabled = function() {
$scope.model.disabled = true;
$scope.title = "Cannot access until mobile number is validated.";
}
} else {
$scope.model.disabled = false;
}
How can I use html tags inside the controller? As my error message is a dynamic one.
Use ng-include.
Js add
$scope.includePath = function () {
`templateUrl="..../your template path"`
};
HTML
<div ng-include="includePath" > New html is here </div>
Here in this case you can use <button> if you want to give click event.
HTML
<div ng-class="{ 'alert': flash, 'alert-success': flash.type === 'success', 'alert-danger': flash.type === 'error', 'selected': hlink}" ng-click = "linking()" ng-if="flash" ng-bind="flash.message" style="margin-top: 20px; ">
</div>
My Controller
if (res.json.response.mobilevalidated == false) {
$scope.linking = function(){
$location.path('/otp');
}
$scope.hlink =" click here";
FlashService.Error("Mobile number not validated." + $scope.hlink +" to validate" , false);
}
What you are looking for can be achieved using $sce that is included in Angular. Take a look at the Documentation here: https://docs.angularjs.org/api/ng/service/$sce
You basically define your HTML string as trusted in the Controller like this: $sce.trustAsHtml(Stackoverflow") and bind it in the template using ng-bind-html like <span ng-bind-html="mySuperCoolLink"></span>.
There is an example in the documentation liked above.
Edit:
Your function FlashService.Error receives an invalid string. You use string concatenation to include your HTML link, however, that only works if your HTML link is stored in a variable. So you have to do one of the following:
A)
FlashService.Error("Mobile number not validated. click here ) to validate", false);
or B)
var link = "( click here )";
FlashService.Error("Mobile number not validated." + link + " to validate", false);
In your provided code, the JS engine will recognise the round brackets as they are valid JS, but not the pointy brackets (I forgot their name...).
Edit 2:
Plunkr: https://plnkr.co/edit/WzzWtnJW98u3e7eTLn2q?p=preview

HTMLService won't display return value

I created a sidebar to have a basic UI for searching my Google sheet. I'm following this tutorial exactly to make sure the first step works, except that it doesn't! I even took out the userObject part to make it simpler (honestly, because I don't know what that part does).
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
function updateButton(email, button) {
button.value = 'Clicked by ' + email;
}
</script>
</head>
<body>
<input type="button" value="Not Clicked"
onclick="google.script.run
.withSuccessHandler(updateButton)
//.withUserObject(this)
.testMe()" />
<input type="button" value="Not Clicked"
onclick="google.script.run
.withSuccessHandler(updateButton)
//.withUserObject(this)
.testMe()" />
</body>
</html>
It calls this function:
function testMe() {
Logger.log("Test log.");
return ContentService.createTextOutput("Jackpot!");
}
If it matters, the HTML runs in a sidebar via onOpen as follows:
function showGradingSidebar() {
var html = HtmlService.createHtmlOutputFromFile('testSidebar')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('Testing Module')
.setWidth(300);
SpreadsheetApp.getUi()
.showSidebar(html);
}
When I click the button, it does nothing (that I can see). By changing various aspects, I can get it to Logger.log() a simple message but even that doesn't work reliably if I change the HTML side.
I was reading about the security restrictions that require sanitizing what the function returns, but both HtmlService.createHtmlOutput() and ContentService.createTextOutput() were also unsuccessful. Please advise.
UPDATE: Thanks to #Bryan P, I got it to work. The testMe() is simply:
return "Jackpot";
...and the HTML page looks like this:
[html, head, etc.]<body>
<input type="button" value="Ready"
onclick="google.script.run
.withSuccessHandler(updateButton)
.withUserObject(this)
.testMe()" --->
<br><div id="output">Output goes here: </div>
<br><div id="papa">Papa goes here: </div>
<br><p></p>
<script>
function updateButton(result) {
var div = document.getElementById('output')
div.innerHTML = 'It finally works!' + result;
}
</script>
</body>
</html>
I don't know how much it helped, but I did move the script tag down to the bottom of the body, fwiw, after reading this SO post.
In Chrome, if you right-click in the sidebar area >> Inspect >> in the Console it should show a message that there wasn't a valid return type after clicking on one of the buttons.
.createTextOutput(content) returns a TextOutput type (which isn't the same as just plain text type)
It's only used when you've deployed a the web app URL and some external service calls that URL. It only gets handled with doGet() too.
Did you try just return "Jackpot"; instead?
.withUserObject(this) - this refers to button element and the whole method passes it on to the successHandler(). So you can consider keeping it. Otherwise you'd have to reference the button from within the successHandler another way:
function updateButton(email) {
document.getElementById('myButton').value = 'Clicked by ' + email;
}
...which requires you add an ID attribute into the button.
You can always do:
function updateButton(email, button) {
console.log('Success hit');
button.value = 'Clicked by ' + email;
}
...to check whether the successHandler was even called in that Chrome dev console too.

HTML form validation with Google Apps Script's HTML Service

I'm trying to use HTML form validation when using Google Apps Script's HTML Service. As another user asked, according to the documentation example, you must use a button input instead of a submit input. Using a submit button seems to do the validation, but the server function is called anyway. The answer given to that user didn't work for me. Also, I want to call two functions when submitting the form and this can make it more complex.
This is what I'm trying to do: The user fills a form and I generate a Google Doc and give him the URL. When he clicks the submit button, I show him a jQuery UI dialog saying "Your document is being created" with a nice spinner. Then, when the document is generated, I give him the link. I use the success handler to show the result when the Google Doc stuff is finished, but meanwhile I need a function to show the spinner. I don't know if there is a better way to do that than adding another function to the onclick event and maybe it can be damaging the process in some way. Is there a way not to call any of these functions if the form is not valid (using HTML validation)?
This is a simplified version of my code:
Code.gs
function generateDocument(formObject) {
var doc = DocumentApp.create("Document name");
...
return doc.getUrl();
}
Page.html
<main>
<form id="myForm">
...
<input type="button" value="Generate document"
onclick="showProgress();
google.script.run
.withSuccessHandler(openDocument)
.generateDocument(this.parentNode);"/>
</form>
<div id="dialog-confirm" title="Your document">
<div id="dialog-confirm-text"></div>
</div>
Javascript.html
$( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: false, modal: true });
function showProgress() {
$( "#dialog-confirm" ).dialog({ buttons: [ { text: "Cancel", click: function() { $( this ).dialog( "close" ); } } ] });
$( "#dialog-confirm" ).dialog( "open" );
$( "#dialog-confirm-text" ).html( "<br />Wait a second, your document is being generated...<br /><br /><img src='http://i.stack.imgur.com/FhHRx.gif' alt='Spinner'></img>" );
return false;
}
function openDocument(url) {
$( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: false, width: 400, buttons: [ { text: "Ok", click: function() { $( this ).dialog( "close" ); } } ] });
$( "#dialog-confirm-text" ).html( '<br />Click here to open and print your document!' );
return false;
}
All three HTML docs are joined together (and working with its respective tags) with the include function as recommended in the documentation.
The Cancel button in the dialog will close it but won't stop the doc being created. Is it possible to stop this process?
Here's a solution that I found:
"<input type='submit' onclick='if(verifyForm(this.parentNode)===true){google.script.run.withSuccessHandler(YOUROUTPUT).YOURFUNCTION(this.parentNode); return false;}' value='Submit'></form>";
JavaScript side
function verifyForm(){
var elements = document.getElementById("myForm").elements;
for (var i = 0, element; element = elements[i++];) {
if (element.hasAttribute("required") && element.value === ""){
resetInputs();
return false;
}
if (element.hasAttribute("pattern")){
var value = element.value;
if(value.match(element.pattern)){
}else{
resetInputs();
return false;
}
}
}
return true;
}
Calling the window has issues in iOS sometimes, which is why I investigated this further.
Move the function call to the <form> element; remove any function call from the submit input element; and put intermediary JavaScript code into a <script> tag:
<input tabindex="9" type="submit" value="Save Input" id='idInputBtn'>
<form id="myInputForm" name="input" onsubmit="fncWriteInput(this)">
<script>
window.fncWriteInput= function(argTheInfo) {
// Do additional checks here if you want
var everythingIsOk = . . . . . . . ;
if (everythingIsOk) {
google.script.run
.withSuccessHandler(openDocument)
.generateDocument(argTheInfo);
};
};
Notice that this.parentNode gets removed to the arg of the function call, and just use this in the function argument because the function is getting called from the <form> element, which is the parent.
If there are any errors, the form will not be submitted, and the user will get a msg that something was wrong. No code will run.
This is pseudo code, but I do use a set up like this in my application. But use developer tools and you can put a break point right in your browser and step through every line to test it without needing to put in console.log statements.

Google CSE open in new window

I would like to integrate the Google Search bar into my site, and using the default code by Google CSE I have:
<div id="cse-search-form" style="width: 100%;">Loading</div>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function() {
var customSearchOptions = {};
var imageSearchOptions = {};
imageSearchOptions['layout'] = google.search.ImageSearch.LAYOUT_POPUP;
customSearchOptions['enableImageSearch'] = true;
customSearchOptions['imageSearchOptions'] = imageSearchOptions;
var customSearchControl = new google.search.CustomSearchControl(
'003243520079760326318:WMX-1462312306', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
var options = new google.search.DrawOptions();
options.setSearchFormRoot('cse-search-form');
options.setAutoComplete(true);
customSearchControl.draw('shop.htm/cse', options);
}, true);
Followed by the style and the </div>
But I do not want the results to open on the same page, I want them to open in searchresults.htm which has the container div
<div id="cse" style="width:100%;"></div>
if I put in this form:
<form action="http://www.amberantiques.com/searchresults.htm" id="cse-search-box">
<fieldset style="border:none;">
<input type="hidden" name="cx" value="003243520079760326318:WMX-1462312306" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="31" />
<input type="submit" name="sa" value="Search" />
</fieldset>
</form>
Then the form sends it to the page but doesnt run the search, but if you then use the Google bar on the page, it runs the search fine.
Basically, how do you get the google bar to open the results page?
Cheers
If you upgrade to the latest Google Code V2 then you can achieve this by editing code you paste to show results.
<gcse:search></gcse:search>
Change this to
<gcse:search linktarget="_parent"></gcse:search>
When you're building the code for your Google CSE, one of the Look and Feel options is "Two Page" - which will allow you to search on one page, and display the results on another.
The V2 code for the Custom Search (free) or Site Search (paid) gives you a range of options for searching and displaying results on the same page or having it's own result page.
By default this WILL open all result links in a new tab or window.
I had the issue where I needed the search results to open on the same tab/window.
I adjusted the following code
<gcse:search></gcse:search>
to this
<gcse:search linktarget="_self"></gcse:search>
I guess if for some reason your default behavior is not opening in a new tab/window and you need it to then you could try the following
<gcse:search linktarget="_blank"></gcse:search>
Hope this helps.
Can you test by putting this code?
options.enableSearchboxOnly("http://www.amberantiques.com/searchresults.htm");
between this line
var options = new google.search.DrawOptions();
and this line
options.setSearchFormRoot('cse-search-form');
Then put the following code in searchresults.htm
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
function parseQueryFromUrl() {
var queryParamName = "q";
var search = window.location.search.substr(1);
var parts = search.split('&');
for (var i = 0; i < parts.length; i++) {
var keyvaluepair = parts[i].split('=');
if (decodeURIComponent(keyvaluepair[0]) == queryParamName) {
return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' '));
}
}
return '';
}
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl(
'003243520079760326318:WMX-1462312306', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
var queryFromUrl = parseQueryFromUrl();
if (queryFromUrl) {
customSearchControl.execute(queryFromUrl);
}
}, true);
</script>
If this doesn't work you can simply read the documentation provided by google. You'll get your desired information in Designing the Look and Feel with the Control Panel section. Or you may find it in Designing the Look and Feel with XML section. I think you are looking for two page layout.
Another option is to go to http://www.google.com/cse/manage/all and then use the control panel there to customize your search engine as you desire.
Building on the code above, you could use:
<gcse:search newWindow="true"></gcse:search>
According to Google's documentation.
Not obvious from looking at the Google documentation (a familiar story) but you can do this very simply using the v2 Custom Search code by selecting the 'Results only' option in the 'Look and Feel' section:
Click 'Save and Get Code' and paste into your searchresults.htm page.
You now just need to create a simple search box that points to that page which you can put in your page header.
e.g.
<form action="http://www.amberantiques.com/searchresults.htm">
<input type="search" name="q"/>
<input type="submit" value="Go"/>
</form>