return 2 values javascript - javascript

I'm trying to return two values in GAS like this:
Html
<script>
function phoneSearch() {
var phone = document.getElementById("phone").value;
google.script.run.withSuccessHandler(onSuccess).phoneSearch(phone);
}
function onSuccess(name, email) {
document.getElementById('nameDiv').innerHTML = "<div>" + name + "</div>";
document.getElementById('emailDiv').innerHTML = "<div>" + email+ "</div>";
}
</script>
Server JS
function phoneSearch(phone){
try {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("sheetNameHere");
var data = sheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
if (data[i][4] == phone) {
var name = inputData[i][3];
var email = inputData[i][5];
return name;
return email;
}
}
} catch(e) {
alert(e)
}
}
Only the first value (name) returns. Thanks in advance!

You can't use more one 'return' at the same level, you should return object containing your two values.
return {
phone: phone,
email: email
}

You can only return 1 value from your function at a time, but you can easily wrap that in an object:
<script>
function phoneSearch() {
var phone = document.getElementById("phone").value;
google.script.run.withSuccessHandler(onSuccess).phoneSearch(phone);
}
function onSuccess(result) {
// ^ phoneSearch now returns -one- object, containing `name` and `email`.
document.getElementById('nameDiv').innerHTML = "<div>" + result.name + "</div>";
document.getElementById('emailDiv').innerHTML = "<div>" + result.email+ "</div>";
}
</script>
JS
function phoneSearch(phone){
try {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("sheetNameHere");
var data = sheet.getDataRange().getValues();
for (var i = 1; i < data.length; i++) {
if (data[i][4] == phone) {
var name = inputData[i][3];
var email = inputData[i][5];
// Return both values at once.
return { name, email };
// (This is shorthand for: `return { name: name, email: email };`)
}
}
} catch(e) {
alert(e)
}
}

Related

How to open and makes query to sqlite database with JavaScript

I'm trying to do a client-side database visualizer with JS. I have never used JavaScript for doing this type of stuff, so I searched online and I found out this web page. This is the script that I have done.
<html>
<head>
<script>
function handleFiles(files)
{
var file = files[0];
var reader = new FileReader();
reader.readAsBinaryString(file);
openSqliteDb(reader);
}
function openSqliteDb(reader)
{
setTimeout(function () {
if(reader.readyState == reader.DONE)
{
var database = SQL.open(bin2Array(reader.result));
document.write("2");
executeQuery("SELECT * FROM User", database);
}
else
{
openSqliteDb(reader);
}
}, 500);
}
function executeQuery(commands, database)
{
document.write("1");
commands = commands.replace(/n/g, '; ');
try {
var data = database.exec(commands);
document.write(data);
processData(data);
} catch(e) {
console.log(e);
}
}
function processData(data)
{
document.write("1");
var colHeaders = [];
var colMap = {};
var tableContent = [];
var tableHtml = [];
tableHtml.push("<table border='1' cellspacing='2' cellpadding-'3'>");
for (var i = 0; i < data.length; i++) {
tableContent.push("<tr>");
var dataElem = data[i];
if (dataElem instanceof Array) {
for (var j = 0; j < dataElem.length; j++) {
var element = dataElem[j];
if (element.column && !colMap[element.column]) {
colHeaders.push("<th>" + element.column + "</th>");
colMap[element.column] = colHeaders.length;
tableContent.push("<td> " + element.value + "</td>");
} else {
tableContent.push("<td> " + element.value + "</td>");
}
}
} else {
if (element.column && !colMap[element.column]) {
colHeaders.push(element.column);
colMap[element.column] = colHeaders.length;
}
}
tableContent.push("</tr>");
}
tableHtml.push(colHeaders.join(" "));
tableHtml.push(tableContent.join(" "));
tableHtml.push("</table>");
document.getElementById("table").innerHTML = tableHtml.join(" ");
}
</script>
</head>
<body>
<input type="file" id="input" onchange="handleFiles(this.files)">
</body>
</html>
I can't figure it out why it is not working, but I think that the problem is the line var database = SQL.open(bin2Array(reader.result)); in the openSqliteDb() function. Can somebody help me?

How to send a variable back from foreground.js to background.js

I tried to send my variable back from foreground.js to background.js by using an unchanged variable, and it works. Now I can't send some data that I use my AddEventListener syntax to store the data into the variable to call its back to background.js here are my code on foreground.js
foreground.js
console.log("foreground.js injected");
var pswdBtns = [];
let hrefLists = [];
var data = {};
var i;
function readUUID(){
var navigator_info = window.navigator;
var screen_info = window.screen;
var uid = navigator_info.mimeTypes.length;
uid += navigator_info.userAgent.replace(/\D+/g, '');
uid += navigator_info.plugins.length;
uid += screen_info.height || '';
uid += screen_info.width || '';
uid += screen_info.pixelDepth || '';
return uid;
}
async function passwordProtected(pointerList){
const date = new Date();
const uid = readUUID();
alert("You are in dangerous on \'"+ pointerList.title + "\' row = " + pointerList.id.slice(20));
data = {
"Webtitle": pointerList.href,
"Title": pointerList.title,
"Time": date.toString(),
"UUID": uid
}
console.log("foreground = ", data);
return data;
}
console.log("Start loop")
//This function made for collect each id in passwordShowPasswordButton
for(i = 0; i<=pswdBtns.length; i++){
if(document.querySelector("#passwordShowPasswordButton_"+ i) == null){
console.log("This is your limit!!");
}
else{
hrefLists[i] = document.querySelector("#passwordWebsitelink_"+ i);
pswdBtns[i] = document.querySelector("#passwordShowPasswordButton_"+ i);;
data = pswdBtns[i].addEventListener('click', passwordProtected.bind(pswdBtns[i], hrefLists[i]));
console.log(hrefLists[i].title); /* Title VARCHAR(30) */
console.log(hrefLists[i].href); /* Website VARCHAR(50) */
}
}
console.log("End");
and these are my code on background.js
background.js
const edgePswd = "edge://settings/passwords";
const settingPage = "edge://settings/";
chrome.tabs.onActivated.addListener(async (tab) => {
await chrome.tabs.get(tab.tabId, (current_tab_info) => {
var pswdPageChecked = 1;
while(pswdPageChecked < 2) {
if (edgePswd == current_tab_info.url) {
chrome.tabs.executeScript(null, { file: "/extension/foreground.js" }, (data) => {
console.log("Coming to foreground");
console.log(data);
});
pswdPageChecked++;
}
}
});
});
It would be a pleasure if someone can figure this.

Delay for messages in node-telegram-bot-api

I am working on a telegram bot with the node-telegram-bot-api library. I made 2 buttons using keyboard. But when you click on them a lot, the bot will spam and sooner or later it will freeze. Is it possible to somehow put a delay for the user on messages.
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
export const keyboardMain = {
reply_markup: JSON.stringify({
keyboard: [
[{
text: '/start',
},
],
resize_keyboard: true
})
};
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use:
You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
I tried using this code, put the function code in my function file, connected everything to the required file, and I don’t understand what to do next and where to insert the last code and what to do with it. I'm new to JavaScript and just learning.
import {
bot
} from '../token.js';
import {
throttler
} from '../functions/functions.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
const throttle = throttler(10);
if (text === '/start') {
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
return bot.sendMessage(chatId, 'hello', keyboardMain);
} else {
// dont reply
}
}
return bot.sendMessage(chatId, 'error');
});
}
Get the time when he pressed the button
Get the time of the next click
Take away the difference and set the condition (if, for example, more than 3 seconds have passed between clicks, then the user will not be frozen).
var token = ""; // FILL IN YOUR OWN TOKEN
var telegramUrl = "https://api.telegram.org/bot" + token;
var webAppUrl = ""; // FILLINYOUR GOOGLEWEBAPPADDRESS
var ssId = ""; // FILL IN THE ID OF YOUR SPREADSHEET
function getMe() {
var url = telegramUrl + "/getMe";
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function setWebhook() {
var url = telegramUrl + "/setWebhook?url=" + webAppUrl;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function sendText(id,text) {
var url = telegramUrl + "/sendMessage?chat_id=" + id + "&text=" + text;
var response = UrlFetchApp.fetch(url);
Logger.log(response.getContentText());
}
function doGet(e) {
return HtmlService.createHtmlOutput("Hi there");
}
function doPost(e){
var data = JSON.parse(e.postData.contents);
var text = data.message.text;
var id = data.message.chat.id;
var msgbegan = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A7").getValue();
var msginfo = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A9").getValue();
var answer = "%0A" + msgbegan + "%0A" ;
///////////////////////
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
// global 10 second throttler
const throttle = throttler(500) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}
///////////////////////////////////////
if(text == "/start"){
sendText(id, answer);
} else if (text == "/info"){
sendText(id, msginfo);
}else{
if (text.length == 10){
var found = false;
var total_rows = SpreadsheetApp.openById(ssId).getSheets()[0].getMaxRows();
for(i=1; i<=total_rows; i++){
var loop_id = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(i,2).getValue();
if(text == loop_id){
found = true;
found_at = i; // employee row
break;
}
}
if(found){
sendText(id, work_message);
}else{
var msgerrror = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A6").getValue();
var not_found = "%0A" + msgerrror+ "%0A" ;
sendText(id, not_found);
}
} else {
sendText(id, "eroor");
}
}
/////////////
var emp_name = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,1).getValue();
var emp_work = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,3).getValue();
var homeloc = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,4).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var emp_data = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,5).getValue();
var emp_day = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,6).getValue();
var emp_clock = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,7).getValue();
var emp_location = SpreadsheetApp.openById(ssId).getSheets()[0].getRange(found_at,8).getValue();
var welcome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A2").getValue();
var msgemp = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A3").getValue();
var msgloc = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A4").getValue();
var msgbay = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A5").getValue();
var msghome = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A8").getValue();
var msmobil = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A11").getValue();
var mstoday = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A13").getValue();
var msdata = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A14").getValue();
var msclock = SpreadsheetApp.openById(ssId).getSheets()[1].getRange("A15").getValue();
var work_message = welcome + emp_name +
"%0A" + msgemp + emp_work +
"%0A" + mstoday + emp_day +
"%0A" + msdata + emp_data +
"%0A" + msclock + emp_clock +
"%0A" + msghome + homeloc +
"%0A" + msgloc+ emp_location +
"%0A" + msgbay +
"%0A" + msmobil ;
}
Excuse me . I am a beginner
Is this the correct way

JavaScript mail subject/ message autofill

I am trying to autofill the subject and message fields in an Outlook email using mailto:. Please, see the JavaScript below. Any suggestions? Thank you in advance. (besides, I am a newbie)
function submitForm()
{
changeName();
printPDF();
sendEmail();
}
function changeName()
{
var title = document.getElementById('salesOrder').value
+" ";
title +=
document.getElementById('Project-Name').value
+" ";
title +=
document.getElementById('Client').value
+" ";
document.title = title;
}
function printPDF()
{
print();
}
function sendEmail()
{
var receivers = document.getElementsByClassName("receiver");
var emailString = "";
for (var i = 0; i < receivers.length; i++)
{
if (receivers[i].checked == true) {
emailString += receivers[i].getAttribute("email")
+";";
}
}
window.location.href = "mailto:"+emailString;
}

How to add data locally in many columns?

someone can help me here ? How do I add data locally in many columns ?
I have tried but...
Below my code,
I tried to create more var like : "var salary = document.forms.MedList.salary.value; var test = document.forms.MedList.test.value;
localStorage.setItem(name, data, salary, test);
" etc, but It does not work...
I have to change my doShowAll function or something like this ?
function SaveItem() {
var name = document.forms.MedList.name.value;
var data = document.forms.MedList.data.value;
localStorage.setItem(name, data);
doShowAll();
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var list = "<tr><th>Nome</th><th>Estoque</th></tr>\n";
var i = 0;
for (i = 0; i <= localStorage.length - 1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
if (list == "<tr><th>Nome</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot store Med list as your browser do not support local storage');
}
}
Your best bet is to create an object and store that e.g.
var myObject = {
name: document.forms.MedList.name.value,
data: document.forms.MedList.data.value
}
localStorage.setItem("yourKey", JSON.stringify(myObject));
When you want to grab it out you can do:
var myObject = JSON.parse(localStorage.getItem("yourKey"));
and then access the name and data respectively:
myObject.name
myObject.data
If you wanted to store multiple values under one key, the value can be an array:
e.g.
var myObject = {
name: document.forms.MedList.name.value,
data: document.forms.MedList.data.value
}
var myObject2 = {
name: document.forms.MedList2.name.value,
data: document.forms.MedList2.data.value
}
localStorage.setItem("yourKey", JSON.stringify([myObject, myObject2]));

Categories

Resources