Google search from webpage - html

I'm building a simple webpage.
I wanna select the text inside a <div> and then open a new tab in the same browser and do a Google search for that text with the click of a button. Right now, I just have the solution to copy to clipboard with a button click. Is there any workaround for this...?
I'm OK with using either Google Chrome or Firefox as it's just for a local project. Not meant for public hosting.
UPDATE : I actually need to copy text which is rendered by other HTML code inside the div. I don't wanna copy the code inside the div also.
For reference, here is a code snippet that I used to make my copy to clipboard function.
JavaScript:
function CopyToClipboard(containerid) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid));
range.select().createTextRange();
document.execCommand("copy");
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
document.execCommand("copy");
alert("Copied the text. Use Ctrl+V to paste on Google")
}
}
HTML:
<div class="search" id="div1">
<!--Text to search for (here, CEO of Google)-->
<span>CEO of Google</span>
</div>
<button id="button1" class="button" onclick="CopyToClipboard('div1')">Copy question</button>
This code selects just the text inside the div and then copies it. I don't wanna search for the rest of the code....

Try with the code below.
You can find out more information about how to redirect from your page here.
<html>
<body>
<div id="search_this">New text</div>
<button type="button" onclick="myButtonOnClick()">Search!</button>
</body>
<script>
function myButtonOnClick(){
let url = "https://www.google.com/search?q=";
let searchText = document.getElementById("search_this").innerHTML;
debugger;
window.open(url + searchText);
}
</script>
</html>

This code does the job:
function searchMe() {
var stringQuery = document.getElementById('text_div').innerHTML;
var query = "https://www.google.com/search?q=" + stringQuery.split(' ').join('+');
window.open(query);
}
<div id="text_div" onClick="searchMe();">
Kittens
</div>
Note: Does not work here on stackoverflow but I've tested it in a custom html file and it works.

OK I've got a workaround. Hope it helps someone else with the same problem. A special thanks to both #Daan Seuntjens and #Alex Dragnea for sharing answers as I have used their basic method.
Here, I've selected the text in the <div> and stored it int the range variable which was used earlier for the copy to clipboard function. And then, I did I used another variable query just like both the answers earlier told to add the text https://www.google.com/search?q= to the beginning of the text. And then, I did window.open(query); to open it in another tab and then do a Google search..
NOTE : This code doesn't run here on Stack Overflow. But, I have tested it externally. It is verified and ready to go...
function search(containerid) {
if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(containerid));
window.getSelection().addRange(range);
var query = "https://www.google.com/search?q=" + range;
window.open(query);
}
}
<div class="question" id="div1">
<!--Text to search for (here, CEO of Google)....-->
<span>CEO of Google</span>
</div>
<button class="button" onclick="search('div1')">Search</button>

Related

Adding text to document using checkboxes and buttons?

I'm creating an apps script add-on for google docs(word-like), I created a sidebar with check boxes and a button and want to print specific text into the document after I click the button and depending on which check boxes I have highlighted, so far I managed to create the sidebar with the Html components but I can't manage to print the text in the document.
<link href="https://ssl.gstatic.com/docs/script/css/add-ons.css" rel="stylesheet">
<div class="sidebar">
<div class="elements">
<input type="checkbox" id="myCheck1">Check Box 1<br>
<input type="checkbox" id="myCheck2">Check Box 2<br><br>
<button class="blue" id="process" onclick="myFunction()">Print</button><br><br>
<p id="text1" style="display:none">Checkbox1 is CHECKED!</p>
<p id="text2" style="display:none">Checkbox2 is CHECKED!</p>
</div>
</div>
<script>
function myFunction() {
var checkBox1 = document.getElementById("myCheck1");
var checkBox2 = document.getElementById("myCheck2");
var text = document.getElementById("text1");
var text = document.getElementById("text2");
if (checkBox1.checked == true){
text1.style.display = "block";
} else {
text1.style.display = "none";
}
if (checkBox2.checked == true){
text2.style.display = "block";
} else {
text2.style.display = "none";
}
}
</script>
This is the Html I have for the sidebar and tried an example I found online to print the text but this will print the text on the sidebar bellow the button not on the document.
function onInstall() {
onOpen();
}
function onOpen() {
DocumentApp.getUi()
.createAddonMenu() // Add a new option in the Google Docs Add-ons Menu
.addItem("KO Addon", "showSidebar")
.addToUi(); // Run the showSidebar function when someone clicks the menu
}
function showSidebar() {
var html = HtmlService.createTemplateFromFile("KO")
.evaluate()
.setTitle("KO Addon Options"); // The title shows in the sidebar
DocumentApp.getUi().showSidebar(html);
}
And this is the main code to add the sidebar to the document, I was only able to print things on the document with code on the main but I just don't know how to make them work together, any help would be greatly appreciated,
Thanks.
You want to put the values retrieved from HTML side to Google Document.
If my understanding for your question is correct, how about this sample? In your case, when the values of HTML side send to Google Apps Script, you can achieve it using google.script.run.
Sample script:
HTML side:
Please add the following script to the end of myFunction() at HTML side.
google.script.run.putValues({checkBox1: checkBox1.checked, checkBox2: checkBox2.checked});
GAS side:
Please add the following function to Google Apps Script.
function putValues(obj) {
var body = DocumentApp.getActiveDocument().getBody();
body.appendParagraph(JSON.stringify(obj));
}
Note:
In this sample, it supposes that your script shows the side bar on Google Document and it works fine.
After you modified your script, please open the side bar. When the push button is clicked, the values of check boxed are sent to Google Apps Script and put the values to the active Document.
This is a simple sample script. So please modify it to your situation.
References:
google.script.run
If I misunderstand your question, please tell me. I would like to modify it.

HTML text field input -> site on my page

I have a problem with my HTML-Website.
I would like to have a text field which generates a link after entering and pressing a button from the input. For example, in the text field is "development" and by pressing the button should my browser go to "www.laurensk.at/development".
I donĀ“t have the code for that...
I've understood your question, you can do it using JQuery or Javascript
$("#btnGoto").click(function(){
window.location="www.laurensk.at/"+$("#txtPage").val();
});
I hope this will help you.
You can use the addEventListenerfunction to generate the link when there is a new input in the field.
Example:
var path = document.getElementById("path")
var link = document.getElementById("link")
function makeLink() {
link.href = "http://my.web.site/" + path.value
link.innerHTML = "http://my.web.site/" + path.value
}
path.addEventListener("keyup", makeLink)
<input id="path"/>
<br>
<a id="link" target="_blank"></a>
Documentation: EventTarget.addEventListener() - Web APIs | MDN

Google Sites checkbox value in Google Spreadsheet

On Google sites on edit mode, I have prepared a checkbox using Insert - HTML Box
and within the HTML Box the following code..
<style>
div{
width:100px;
height:30px;
}
</style>
<script>
function putResult(e) {
var ss = SpreadsheetApp.openById("0AkkxdNrvyzqzdE1yU21FRGJ6akJ6MmZiSVhTN0JMNnc");
var calc = ss.getSheetByName("Customer");
var chvalue = e.parameter.bike
calc.getRange("C3").setValue("chvalue");
}
</script>
<div>
EDC:
<input type="checkbox" id="bike" onclick="putResult(e)">
</div>
Now my requirements:
I want simply a True/False based on checkbox to be populated in the SS.Calc (C3) Sheet.
The page should automatically be refreshed each time the checkbox is clicked.
I am a novice and in learning stage. Please do shout if things are unclear.
PS:
I copied some code within GAS, that's where the e.parameter.bike comes from, don't know if that's the right way...
I have also inserted a chart in the Google sites with source data from spreadsheet (insert Chart), I want to make it dynamic using checkboxes.
Old but, since April 2018 they implemented a checkbox in spreadsheets.
You can find it in Menu > insert > checkbox or if you add a datavalidation.
Dealing with your Task by simply checking the field value with
=IF(A1=TRUE();"Checked";"Unchecked")
should be way more easy now! It also instantly checks state changes.
I think HTML Box is not accepting onclick , not sure but by inspecting the checkbox in firebug you can see that there is no onclick for the element.
I think you can do it using google app script as follows,
In code.gs file,
function doGet() {
return HtmlService.createHtmlOutputFromFile('Test').setSandboxMode(HtmlService.SandboxMode.NATIVE);
}
and have file called Test.html.This can be created File --> New --> Script File, in that have the following code,
<style>
div{
width:100px;
height:30px;
}
</style>
<script>
function putResult() {
var ss = SpreadsheetApp.openById("0AkkxdNrvyzqzdE1yU21FRGJ6akJ6MmZiSVhTN0JMNnc");
var calc = ss.getSheetByName("Customer");
var chvalue = document.getElementById('bike').value;
calc.getRange("C3").setValue("chvalue");
}
</script>
<div>
EDC:
<input type="checkbox" id="bike" onclick="putResult()">
</div>
I haven't tested the above code.Try this if it works for you.

chrome extension which will read text inside the particular TAG?

I am trying to create chrome extension which will read text inside the particular TAG from the Webpage ...
but not able to read value
I need to pick Text inside the tag definition excluding html tags..
here i want to read the value from the tag "definition"
output:is an overwhelming urge to have of something is often connected with money
suppose web page is like this
<div id="definition">
<div class="section blurb">
<p class="short"><i>Greed</i> is an overwhelming urge to have <i>more</i>
of something
<p class="long"><i>Greed</i> is often connected with money</p>
</div>
</div>
this is what i was trying
popup.html
<script>
var newwin = chrome.extension.getBackgroundPage();
newwin.get();
</script>
background.html
<Script>
function get()
{
var myDivObj = document.getElementById("definition");
if ( myDivObj ) {
alert (myDivObj.innerHTML);
}else{
alert ( "Alien Found" );
}
}
</Script>
I moved my script from the background page to content scrit and it worked like charm..
but was just wondering why dint work in background page..?

Ideas for multicolored textbox?

In my site, I would like to implement a textbox where people can input a set of strings separated by a separator character.
For example the tags textbox at the bottom of this page: tags(strings) delimited by space(separator).
To make it more clear to the user, it would make a lot of sence to give each string a different background color or other visual hint.
I don't think this is possible with a regular input[text] control.
Do you deem it possible to create something like that with javascript? Has somebody done this before me already? Do you have any other suggestions?
Basic Steps
Put a textbox in a div and style it too hide it.
Make the div look like a text box.
In the onClick handler of the div, set the input focus to the hidden text box.
Handle the onKeyUp event of the hidden text box to capture text, format as necessary and alter the innerHtml of the div.
Tis quite straightforward. I'll leave you to write your formatter but basically you'd just splitString on separator as per the Semi-Working-Example.
Simple Outline
<html>
<head>
<script language="javascript" type="text/javascript">
function focusHiddenInput()
{
var txt = document.getElementById("txtHidden");
txt.focus();
}
function formatInputAndDumpToDiv()
{
alert('Up to you how to format');
}
</script>
</head>
<body>
<div onclick="focusHiddenInput();">
Some label here followed by a divved textbox:
<input id="txtHidden" style="width:0px;" onKeyPress="formatInputAndDumpToDiv()" type="text">
</div>
</body>
</html>
Semi-Working Example
You still need to extend the click handlers to account for tag deletion/editing/backspacing/etc via keyboard.... or you could just use a click event to pop up another context menu div. But with tags and spacer ids identified in the code below that should be pretty easy:
<html>
<head>
<script language="javascript" type="text/javascript">
var myTags=null;
function init()
{
document.getElementById("txtHidden").onkeyup= runFormatter;
}
function focusHiddenInput()
{
document.getElementById("txtHidden").focus();
}
function runFormatter()
{
var txt = document.getElementById("txtHidden");
var txtdiv = document.getElementById("txtBoxDiv");
txtdiv.innerHTML = "";
formatText(txt.value, txtdiv);
}
function formatText(tagText, divTextBox)
{
var tagString="";
var newTag;
var newSpace;
myTags = tagText.split(' ');
for(i=0;i<myTags.length;i++) {
newTag = document.createElement("span");
newTag.setAttribute("id", "tagId_" + i);
newTag.setAttribute("title", myTags[i]);
newTag.setAttribute("innerText", myTags[i]);
if ((i % 2)==0) {
newTag.style.backgroundColor='#eee999';
}
else
{
newTag.style.backgroundColor='#ccceee';
}
divTextBox.appendChild(newTag);
newTag.onclick = function(){tagClickedHandler(this);}
newSpace = document.createElement("span");
newSpace.setAttribute("id", "spId_" + i);
newSpace.setAttribute("innerText", " ");
divTextBox.appendChild(newSpace);
newSpace.onclick = function(){spaceClickedHandler(this);}
}
}
function tagClickedHandler(tag)
{
alert('You clicked a tag:' + tag.title);
}
function spaceClickedHandler(spacer)
{
alert('You clicked a spacer');
}
window.onload=init;
</script>
</head>
<body>
<div id="txtBoxDivContainer">
Enter tags below (Click and Type):<div id="txtBoxDiv" style="border: solid 1px #cccccc; height:20px;width:400px;" onclick="focusHiddenInput();"></div>
<input id="txtHidden" style="width:0px;" type="text">
</div>
</body>
</html>
Cursor
You could CSS the cursor using blink (check support) or otherwise just advance and hide as necessary an animated gif.
This is quite interesting. The short answer to your question is no. Not with the basic input element.
The real answer is: Maybe with some trickery with javascript.
Apparently Facebook does something close to this. When you write a new message to multiple persons in Facebook, you can type their names this sort of way. Each recognized new name is added a bit like an tag here and has an small cross next to it for removing it.
What they seem to do, is fake the input area size by drawing an input-looking box and removing all styling from the actual input with css. Then they have plenty of logic done with javascript so that if you have added an friend as a tag and start backspacing, it will remove the whole friends name at once. etc.
So, yes, it's doable, but takes plenty of effort and adds accessibility problems.
You can look how they do that at scripts like TinyMCE, which add such features to textareas. In textareas you can use HTML to colorize text.
You can use multiple textboxes
textbox1 <space> textbox2 <space> textbox3 ....
and so on... You can then apply the background-color style to each textbox.