Create a custom function for google sheets - javascript

I know it's possible to create a function in google sheets via the script editor, I used to be able to do it, now I'm struggling.
These functions should be accessible through a cell, and be able to use a cell.
How do I create a function, and how do I use it?

It's all described quite extensively in the docs:
https://developers.google.com/apps-script/guides/sheets/functions
To write a custom function:
function DOUBLE(input) {
return input * 2;
}
Create or open a spreadsheet in Google Sheets.
Select the menu item Tools > Script editor. If you are presented with a welcome screen, click Blank Project on the left to start a new project.
Delete any code in the script editor. For the DOUBLE function above, simply copy and paste the code into the script editor.
Select the menu item File > Save. Give the script project a name and click OK.
All done! Now you can use the custom function.
Using a custom function:
Click the cell where you want to use the function.
Type an equals sign (=) followed by the function name and any input value — for example, =DOUBLE(A1) — and press Enter.
The cell will momentarily display Loading..., then return the result.

Related

Google document add-on - setSelection() of text by sidebar button - how to make it an active selection?

Background:
I am using the setSelection() method in an google marketplace add-on for google documents.
The text is selected as expected when clicking the relevant button on the add-on's sidebar. However, this selection is not active - i.e. the selected text is highlighted in light grey instead of light blue (see example below).
Now:
What I need:
This is because the last active portion of the browser tab is the sidebar (after clicking the button), not the actual document.
Question:
Is there a way to make the button click select the text and keep the document the active portion?
Goal:
The whole purpose of this selection is to copy the selected text by Ctrl + C on the keyboard, which is not possible when the selection is not active.
Right now the user needs to use the right-click on the mouse and select Copy from the menu...
On your client-side code use google.script.host.editor.focus() to make the selection on the editor an active selection.
function showSidebar(){
var ui = DocumentApp.getUi();
var html = '<div>Hello world!</div>'
html += '<div><button onclick="google.script.host.editor.focus()">Click me!</button></div>';
ui.showSidebar(HtmlService.createHtmlOutput(html));
}
From https://developers.google.com/apps-script/guides/html/communication#moving_browser_focus_in
Moving browser focus in Google Workspace
To switch focus in the user's browser from a dialog or sidebar back to the Google Docs, Sheets, or Forms editor, simply call the method google.script.host.editor.focus(). This method is particularly useful in combination with the Document service methods Document.setCursor(position) and Document.setSelection(range).
Solution
Since your goal is to copy the selected text I would like to propose an alternative solution:
The task now will include the copying feature directly without additional user input than the button click. And it will be developed this way:
Text Selection
Get your selected text with your Apps Script function triggered by a button click:
//... Your custom logic to get the text selection
var text-to-copy = doc.setSelection(x)
.getSelection()
.getRangeElements()
.map(re => re.getElement()
.asText()
.getText())
.join(" ");
return text-to-copy;
We cannot access the user clipboard from Apps Script but with a successHandler we can pass the text-to-copy variable to the Client-Side interface.
Handling the Server-Side return value
In the following way we can pass the text back to the HTML sidebar.
<!-- HTML Interface Index.html -->
<button onclick="google.script.run.withSuccessHandler(copyToClipboard).setSelection()">
Click Here
</button>
<script>
function copyToClipboard(text) {
const elem = document.createElement('textarea');
elem.value = text;
document.body.appendChild(elem);
elem.select();
document.execCommand('copy');
document.body.removeChild(elem);
}
</script>
We can now leverage the native client-side functionality to copy that text directly to the user clipboard without having her/him to Ctrl+C once your script finished.
A good practice in this case would be to provide a visual feedback to your user once the copy procedure has finished.
Reference
withSuccessHandler(function)

How do I switch between HTML pages in JavaScript

I've made a search bar in my web page and I'm trying to get the user input and compare it to a keyword. If it matches, show the user what he is searching for in another page.
The problem is that I don't know how to switch between pages of the HTML using JavaScript (being in page1.html and then take the user to page2.html if the keyword matches).
I've tried to implement href to a function and then running it when the search button is pressed but I haven't found a way to do it.
Here is the code:
<script>
let search = getElementById("Search").value;
if (search == "Keyword") {
//a href="page2.html" - (this is was my main idea, but i haven't found a way to implement it correctly)
}
</script>
First, you have to get the value from the input that you create and then you have to compare between the value that you get it and the specific keyword that you want, and after that, you have to create a button to submit with it. Then you can try this line
window.location.href=“./Page2.htm”;
inside if condetion.
try with:
window.location.href=“./Page2.htm”;
You can use
window.open(stringURL);
to open the html in a new window.
To open a new tab:
window.open(stringURL, “_blank”);
For more info: https://developer.mozilla.org/en-US/docs/Web/API/Window/open

Can i detect if a web page has been translated by Google?

I have a web page, in Dutch, with a poll with a radio button.
I'd like to know which language the users speak. Is there a way I can detect if the page has been translated by Google when they submit?
I do not use a translation bar, I am talking about the spontaneous google translation.
Just check a known element if the text matches your text.
function isDutch() {
return $('#readmore').text() === "Meer lezen";
}
or a non jQuery solution:
function isDutch() {
document.querySelector('#readmore').innerText === "Meer lezen";
}
Just make sure the element you have is an easy translatable sentence like read more.
Then you update a hidden field in your form with the result.
You can do this the moment a click is registered on your radio button.
I just tested it on a russian site, lenta.ru and ran $('a[href="/parts/news"]').text(); after having translated it by right clicking the page and selecting translate this page(chrome). The content returned was in my language(dutch) in the jquery text().
When translated through Google Translate, the target language is injected into the lang attribute of the main html tag, you can retrieve it with:
document.getElementsByTagName('html')[0].getAttribute('lang')
which results in something like
en-x-mtfrom-nl... and this in turn you can log to your server or set as a cookie.

Edit the code in the opened tab

im doing a plugin to the cloud 9 sdk its basically a simple autocomplete for c language
my issue is that when i complete the name of the function the ide doesn't reserve the change meaning the next time he edit the line it will go back to before the line was edited
for example if i write pri then selected printf then pressed space it will be "pri " not "printf "
here is my code
modifying html inside ace won't work.
If you want to create a new completer, create a lnaguage handler
https://cloud9-sdk.readme.io/docs/customizing-code-completers
which will use built in completer popup
here is what i found
ace.scrollTo(row, column);
clipboard.clipboardData.setData("text/plain", "text to add");
clipboard.paste();
you will need to include clipboard and ace to consumes for that code to work

How to run javascript byc clicking a cell in google sheets?

Google sheets allows you to write scripts in javascript, the same way excel lets you write VBA to automate tasks.
I'd like to make a cell in my google spreadsheet clickable, so that when it is clicked, my function will run.
I've found that it's possible to create custom buttons by inserting a drawing, but I'd really like this to be any time a particular cell is clicked, rather than a button which can move around and looks awkward in the sheet.
Is it possible?
Thanks for any advice.
There is not an onClick event for cells but what you can do is instruct the user to enter your formula/custom function into the cell as described at https://developers.google.com/apps-script/execution_custom_functions?hl=es#using.
Similarly, you could have the cell pre-populated with the formula and simply ask the user to edit it and then press enter to run the function.
What you are searching for, is onSelectionChange(), it runs automatically when a user changes the selection in a spreadsheet.
Try the following code and read the developers link.
/**
* The event handler triggered when the selection changes in the spreadsheet.
* #param {Event} e The onSelectionChange event.
*/
function onSelectionChange(e) {
// Set background to red if a single empty cell is selected.
var range = e.range;
if(range.getNumRows() === 1
&& range.getNumColumns() === 1
&& range.getCell(1, 1).getValue() === "") {
range.setBackground("red");
}
}
You can draw you own button and attach a sript to it. Edit it all transparent, and write no text.
Then place it on the cell you wish, resizing to fit inside the cell's area.
Add A Google Sheets Button To Run Scripts

Categories

Resources