I need with parsing an array from google script to HTML - html

I have a date picker that I'd like to use to choose an event and then show details from a spread sheet.
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker({
onSelect: function(date) {
var stuff= updDate(date);
},
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1,
});
});
</script>
<script>
function updDate(date){
google.script.run.updDate(date);
}
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" onchange="updDate()"></p>
Hello, world!
<input type="button" value="Close"
onclick="google.script.host.close()" />
</body>
</html>
Google Script:
function updDate(date){
var searchString = date;
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var s2 = SpreadsheetApp.openById("*************");
var row = new Array();
var k;
for (var i in data) {
//Logger.log("length is: "+data[i].length)
//var p = data[i].length
for (var j in data[i]) {
//Logger.log("We are at i: "+i) //Row
//Logger.log("We are at j: "+j) //Col
if (i !=0){
if(data[i][j] != ""){
if(j == 4){
//Logger.log("date from picker: " + date);
//Logger.log("date from Data: " + data[i][j]);
var ssDate = Utilities.formatDate(data[i][j], "GMT", "MM/dd/yyyy");
//Logger.log("date post Convert: " +ssDate);
if(date == ssDate){
k= i
var p = data[i].length
Logger.log("P is: " +p);
}
}
}
}
}
}
Logger.log("K is: "+k)
var q = 1
while (q <= p){
row[q] = data[k][q];
q++
}
Logger.log("Row: " +row);
return row;
}
Eventually I'd like to get the data read into a table but I've been hitting a wall when it comes to successfully getting the data read into a variable in the HTML.
Right now I get this error:
Uncaught ScriptError: The script completed but the returned value is not a supported return type.
Any help in returning the array "row"(in the google script) to the variable "stuff"(in the HTML) successfully or any pointers about how to better execute this task would be greatly appreciated.
Loren
Edit code:
function updDate(date){
var stuff = google.script.run.withSuccessHandler(myReturnFunction).updDate(date);
Console.log(stuff)
}
function myReturnFunction(){
window.myReturnFunction = function(whatGotReturned) {console.log(whatGotReturned);};
}

Sandy Good had it right in the comments above:
function updDate(date){
var junk = google.script.run.withSuccessHandler(myReturnFunction).updDate(date);
}
function myReturnFunction(whatGotReturned){
console.log(whatGotReturned);
}

Related

Show div depending to value of function in apps script

I develop and web app in apps script where i can select a name. Each name is in my Sheets and is depending to a profil. I can have 2 possibilities : The name have a profil or doesn't have. In the screenshot below, Sir A have a profil and Sir B and C doesn't have.
I would like to show a div in my html's page if the selected name doesn't have profil (and already hide if the selected name have a profil). So i create a function to detect if the select name have a value written in my Sheets. If it's correct, i write yes in one div (and no if it's not correct). But when i want to show div, it's doesn't work.
To try to understand my problem, i created a button to launch a function where i get the value of my result. I have undefined each time and i don't know why.
This is my html's code :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('JavaScript'); ?>
<?!= include('StyleSheet'); ?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<form>
<!-- NAME -->
<div class="form-row">
<div class="form-group col-md-12">
<label for="name"><b>Name :</b></label>
<select class="form-control" id="name" onChange = "showProfil();">
<option disabled selected>Choose ...</option>
<?!=getNames()?>
</select>
</div>
</div>
<!-- RESULT -->
<div><label> Result : </label><p id = "result"></p></div>
<!-- BUTTON -->
<input type="button" class="btn btn-primary btn-block" value="SHOW DIV ?" id = "btnAccesQuestions" onclick = "showDivResultNo();">
<!-- DIV DISPLAY WHEN RESULT IS NO -->
<div id = "divResultNo">
<h2> Result is "NO"</h2>
</div>
</form>
</body>
</html>
This is my server side code :
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle('Formulaire de demande de formation');
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function getNames(){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Sheet1");
var tNames = feuille.getRange("A2:A").getValues().filter(d =>d[0] !== "").flat();
var names = deleteDuplicateValues(tNames);
return names.map(d => "<option>" + d + "</option>").join("");
}
function deleteDuplicateValues(array) {
var outArray = [];
array.sort(lowerCase);
function lowerCase(a,b){
return a.toLowerCase()>b.toLowerCase() ? 1 : -1;
}
outArray.push(array[0]);
for(var n in array){
if(outArray[outArray.length-1].toLowerCase()!=array[n].toLowerCase()){
outArray.push(array[n]);
}
}
return outArray;
}
function getProfil(name){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Sheet1");
var tProfils = feuille.getRange("A2:B").getValues().filter(d =>d[0] !== "");
for (let i = 0; i < tProfils.length; i ++){
if(tProfils[i][0] == name){
if(tProfils[i][1] == ""){
var resultat = "no";
}
else {
var resultat = "yes";
}
}
}
return resultat;
}
function testProfil(){
Logger.log(getProfil("Sir A"));
}
This is my js code :
<script>
function showProfil(){
var name = document.getElementById("name").value;
google.script.run.withSuccessHandler(profil => {
document.getElementById("result").innerHTML = profil;
}).getProfil(name);
}
function showDivResultNo(){
var name = document.getElementById("name").value;
var result = document.getElementById("result").value;
console.log(result)
if (name != "Choose ..." && name != "" && result == "no"){
console.log("show div after that");
}
else {
console.log("div always hidden");
}
}
</script>
And this is a screenshot of my web app after selected Sir A and press button :
If anyone can help me, it would be appreciated. You can acces to my Sheet in this link. Thank you for advance.
In your script, how about the following modification?
From:
var result = document.getElementById("result").value;
To:
var result = document.getElementById("result").innerHTML;
I thought that from your HTML, I thought that the reason of your issue of I have undefined each time and i don't know why. might be due to .value.

AmCharts4 - Unable to load file - external JSON file produced from SQL database

I'm struggling to open my json arranged data in AmCharts4. In my previous charts I used very simple script (chart.data = ;), which unfortunately does not work this time. So I'm using chart.dataSource.url function proposed by AmCharts documentation. When, I load example file found on web everything works fine, as soon as I switch to my file the chart is not able to load file. I'm not able to find a similar problem on web, therefore I would be very grateful for help.
Here is my example with working url and my not working file.
Thanks in advance:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>
<style>
</style>
</head>
<body>
<div id="chartdiv"></div>
</body>
</html>
<!-- Styles -->
<style>
#chartdiv {
width: 100%;
height: 500px;
}
</style>
<!-- Resources -->
<script src="https://cdn.amcharts.com/lib/4/core.js"></script>
<script src="https://cdn.amcharts.com/lib/4/charts.js"></script>
<script src="https://cdn.amcharts.com/lib/4/themes/animated.js"></script>
<!-- Chart code -->
<script>
am4core.ready(function() {
// Themes begin
am4core.useTheme(am4themes_animated);
// Themes end
var chart = am4core.create('chartdiv', am4charts.XYChart)
// Modify chart's colors
chart.colors.list = [
am4core.color("#264B29"),
am4core.color("#94B255"),
am4core.color("#456C39"),
am4core.color("#C4D563"),
am4core.color("#698F47"),
am4core.color("#F9F871"),
];
chart.legend = new am4charts.Legend()
chart.legend.position = 'top'
chart.legend.paddingBottom = 20
chart.legend.labels.template.maxWidth = 95
var xAxis = chart.xAxes.push(new am4charts.CategoryAxis())
xAxis.dataFields.category = 'year'
xAxis.renderer.cellStartLocation = 0.1
xAxis.renderer.cellEndLocation = 0.9
xAxis.renderer.grid.template.location = 0;
var yAxis = chart.yAxes.push(new am4charts.ValueAxis());
function createSeries(value, name) {
var series = chart.series.push(new am4charts.ColumnSeries())
series.dataFields.valueY = value
series.dataFields.categoryX = 'year'
series.name = name
series.events.on("hidden", arrangeColumns);
series.events.on("shown", arrangeColumns);
var bullet = series.bullets.push(new am4charts.LabelBullet())
bullet.interactionsEnabled = false
bullet.dy = 30;
bullet.label.text = '{valueY}'
bullet.label.fill = am4core.color('#ffffff')
return series;
}
// Add data
//Working url
//chart.dataSource.url = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/sample_data_serial.json";
//My SQL produced JSON file is not working
chart.dataSource.url = "data/my-file.php";
chart.dataSource.adapter.add("parsedData", function(data) {
var newData = [];
data.forEach(function(dataItem) {
var newDataItem = {};
Object.keys(dataItem).forEach(function(key) {
if (typeof dataItem[key] === "object") {
newDataItem["_id"] = dataItem[key]["#id"];
dataItem[key]["Column"].forEach(function(dataItem) {
newDataItem[dataItem["#name"]] = dataItem["#id"];
});
} else {
newDataItem[key] = dataItem[key];
}
});
newData.push(newDataItem);
});
data = newData;
return data;
});
createSeries('cars', 'The First');
createSeries('motorcycles', 'The Second');
createSeries('bicycles', 'The Third');
//createSeries('bilanca_lsk_lst', 'T4');
function arrangeColumns() {
var series = chart.series.getIndex(0);
var w = 1 - xAxis.renderer.cellStartLocation - (1 - xAxis.renderer.cellEndLocation);
if (series.dataItems.length > 1) {
var x0 = xAxis.getX(series.dataItems.getIndex(0), "yearX");
var x1 = xAxis.getX(series.dataItems.getIndex(1), "yearX");
var delta = ((x1 - x0) / chart.series.length) * w;
if (am4core.isNumber(delta)) {
var middle = chart.series.length / 2;
var newIndex = 0;
chart.series.each(function(series) {
if (!series.isHidden && !series.isHiding) {
series.dummyData = newIndex;
newIndex++;
}
else {
series.dummyData = chart.series.indexOf(series);
}
})
var visibleCount = newIndex;
var newMiddle = visibleCount / 2;
chart.series.each(function(series) {
var trueIndex = chart.series.indexOf(series);
var newIndex = series.dummyData;
var dx = (newIndex - trueIndex + middle - newMiddle) * delta
series.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
series.bulletsContainer.animate({ property: "dx", to: dx }, series.interpolationDuration, series.interpolationEasing);
})
}
}
}
});
// end am4core.ready()
</script>
I found a typing error in my-file.php
Anyhow, after I solved typing issue the chart.dataSource.url function still did not work, but It worked using next php include script.
chart.data = <?php include './data/my-file.php'; ?>;

How to get or displaying address and geocode Geolocation in Spreadsheets using web app google script editor?

I want to make my spreadsheets able to displaying data from web app - spreadsheet script editor (geolocation). I want to get my siblings current location. I don't want use Google Form by the way.
How to fix this?
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function getLoc(value) {
var destId = FormApp.getActiveForm().getDestinationId() ;
var ss = SpreadsheetApp.openById(destId) ;
var respSheet = ss.getSheets()[0] ;
var data = respSheet.getDataRange().getValues() ;
var headers = data[0] ;
var numColumns = headers.length ;
var numResponses = data.length;
var c=value[0];
var d=value[1];
var e=c + "," + d ;
if (respSheet.getRange(1,numColumns).getValue()=="GeoAddress") {
if (respSheet.getRange(numResponses,numColumns-2).getValue()=="" && respSheet.getRange(numResponses-1,numColumns-2).getValue()!="" ){
respSheet.getRange(numResponses,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy HH:mm:ss"));
respSheet.getRange(numResponses,numColumns-1).setValue(e);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns).setValue(f);
}
else if (respSheet.getRange(numResponses,numColumns-2).getValue()=="" && respSheet.getRange(numResponses-1,numColumns-2).getValue()=="" ){
respSheet.getRange(numResponses,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy HH:mm:ss")).setFontColor("red");
respSheet.getRange(numResponses,numColumns-1).setValue(e).setFontColor("red");
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns).setValue(f).setFontColor("red");
}
else if (respSheet.getRange(numResponses,numColumns-2).getValue()!=""){
for (i = 0; i < numResponses; i++) {
if (respSheet.getRange(numResponses-i,numColumns-2).getValue()=="") {
respSheet.getRange(numResponses-i,numColumns-2).setValue(Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy HH:mm:ss")).setFontColor("red");
respSheet.getRange(numResponses-i,numColumns-1).setValue(e).setFontColor("red");
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses-i,numColumns).setValue(f).setFontColor("red");
break; }
}
}
}
else if (respSheet.getRange(1,numColumns).getValue()!="GeoAddress") {
respSheet.getRange(1,numColumns+1).setValue("GeoStamp");
respSheet.getRange(1,numColumns+2).setValue("GeoCode");
respSheet.getRange(1,numColumns+3).setValue("GeoAddress");
if (numResponses==2) {
respSheet.getRange(numResponses,numColumns+1).setValue(Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy HH:mm:ss"));
respSheet.getRange(numResponses,numColumns+2).setValue(e);
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns+3).setValue(f);
}
else if (numResponses > 2){
respSheet.getRange(numResponses,numColumns+1).setValue(Utilities.formatDate(new Date(), "GMT+7", "MM/dd/yyyy HH:mm:ss")).setFontColor("red");
respSheet.getRange(numResponses,numColumns+2).setValue(e).setFontColor("red");
var response = Maps.newGeocoder().reverseGeocode(value[0], value[1]);
f= response.results[0].formatted_address;
respSheet.getRange(numResponses,numColumns+3).setValue(f).setFontColor("red");
}
}
}
Index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Absensi Lokasi Online</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<script>
(function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
})()
function showPosition(position) {
var a= position.coords.latitude;
var b= position.coords.longitude;
var c=[a,b]
getPos(c)
function getPos(value) {
google.script.run.getLoc(value);
}
}
</script>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.min.js"></script>
<script>
swal({
title: "Absensi Berhasil",
text: "Jika anda pertama kali absen, silahkan izinkan aplikasi ini mengakses lokasi anda. Terimakasih",
type: "success"
}).then(function() {
window.location.href = "https://forms.gle/JG1oWKvyBRW4bF4V8";
});
</script>
</body>
</html>
The code I get is aim using google form, and I don't want asking location permission through Google form. I want asking for location permission on google script link tho. and when someone agree to allow his location, I want it to displaying data such as geostamp, geocode, geoaddress in spreadsheet.

Google sheet + Web app search multiple google workbook and return all matching rows

Anybody knows how can I amend the code below to search from 2 separate google workbooks? Currently, this only works to search from 1 google sheet in 1 workbook.
Both these sheets have the exact same headers.
When the user searches for a specific text, it should display the matching rows from both workbooks.
Code.gs:
function doGet() {
return HtmlService.createTemplateFromFile('Index')
.evaluate()
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
/* PROCESS FORM */
function processForm(formObject){
var result = "";
if(formObject.searchtext){//Execute if form passes search text
result = search(formObject.searchtext);
}
return result;
}
//SEARCH FOR MATCHED CONTENTS
function search(searchtext){
var spreadsheetId = '1443X5UzzRfpYachZZLFrmYFq821ioioqwFAnASY'; //** CHANGE !!!
var dataRage = 'TEST!A2:F'; //** CHANGE !!!
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
var ar = [];
data.forEach(function(f) {
if (~f.indexOf(searchtext)) {
ar.push(f);
}
});
return ar;
}
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!--##JAVASCRIPT FUNCTIONS ---------------------------------------------------- -->
<script>
//PREVENT FORMS FROM SUBMITTING / PREVENT DEFAULT BEHAVIOUR
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener("load", preventFormSubmit, true);
//HANDLE FORM SUBMISSION
function handleFormSubmit(formObject) {
google.script.run.withSuccessHandler(createTable).processForm(formObject);
document.getElementById("search-form").reset();
}
//CREATE THE DATA TABLE
function createTable(dataArray) {
if(dataArray && dataArray !== undefined && dataArray.length != 0){
var result = "<table class='table table-sm table-striped' id='dtable' style='font-size:0.8em'>"+
"<thead style='white-space: nowrap'>"+
"<tr>"+ //Change table headings to match witht he Google Sheet
"<th scope='col'>Group</th>"+
"<th scope='col'>QO Number</th>"+
"<th scope='col'>Patient NRIC</th>"+
"<th scope='col'>Swab Date</th>"+
"<th scope='col'>Lab ID</th>"+
"<th scope='col'>SERO Lab ID</th>"+
"</tr>"+
"</thead>";
for(var i=0; i<dataArray.length; i++) {
result += "<tr>";
for(var j=0; j<dataArray[i].length; j++){
result += "<td>"+dataArray[i][j]+"</td>";
}
result += "</tr>";
}
result += "</table>";
var div = document.getElementById('search-results');
div.innerHTML = result;
}else{
var div = document.getElementById('search-results');
//div.empty()
div.innerHTML = "Data not found!";
}
}
</script>
<!--##JAVASCRIPT FUNCTIONS ~ END ---------------------------------------------------- -->
</head>
<body>
<div class="container">
<br>
<div class="row">
<div class="col">
<!-- ## SEARCH FORM ------------------------------------------------ -->
<form id="search-form" class="form-inline" onsubmit="handleFormSubmit(this)">
<div class="form-group mb-2">
<label for="searchtext">Swab Search</label>
</div>
<div class="form-group mx-sm-3 mb-2">
<input type="text" class="form-control" id="searchtext" name="searchtext" placeholder="QO or NRIC (last 4 digits)">
</div>
<button type="submit" class="btn btn-primary mb-2">Search</button>
</form>
<!-- ## SEARCH FORM ~ END ------------------------------------------- -->
</div>
</div>
<div class="row">
<div class="col">
<!-- ## TABLE OF SEARCH RESULTS ------------------------------------------------ -->
<div id="search-results" class="table-responsive">
<!-- The Data Table is inserted here by JavaScript -->
</div>
<!-- ## TABLE OF SEARCH RESULTS ~ END ------------------------------------------------ -->
</div>
</div>
</div>
</body>
</html>
Have an array with the ID of the different spreadsheets you want to retrieve data from, and iterate through that:
function search(searchtext){
var spreadsheetIds = ['1443X5UzzRfpYachZZLFrmYFq821ioioqwFAnASY'];
var dataRage = 'TEST!A2:F';
var ar = [];
spreadsheetIds.forEach(spreadsheetId => {
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRage).values;
data.forEach(function(f) {
if (~f.indexOf(searchtext)) {
ar.push(f);
}
});
});
return ar;
}
If the range notation of the different spreadsheets should also change, then have an array with those ranges too, and access each element in the array using the forEach index parameter:
function search(searchtext){
var spreadsheetIds = ['SPREADSHEET_ID_1', 'SPREADSHEET_ID_2'];
var dataRages = ['RANGE_1', 'RANGE_2'];
var ar = [];
spreadsheetIds.forEach((spreadsheetId, i) => {
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRages[i]).values;
data.forEach(function(f) {
if (~f.indexOf(searchtext)) {
ar.push(f);
}
});
});
return ar;
}
Not sure if you want to retrieve more information than just the row index, but if that's the case, just push that information to ar, not just f.
Alternatively, use reduce:
function search(searchtext) {
const spreadsheetIds = ['SPREADSHEET_ID_1', 'SPREADSHEET_ID_2'];
const dataRages = ['RANGE_1', 'RANGE_2'];
const ar = spreadsheetIds.reduce((acc, spreadsheetId, i) => {
const data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRages[i]).values;
return acc.concat(data.filter(f => f.includes(searchText)));
}, []);
return ar;
}
Reference:
Array.prototype.reduce()

How to get info from background_page to popup?

I'm following the official Chrome Extension tutorial called Chritter where they fetch tweets from Twitter and place them into the extension. I'm trying to do similar except im trying to fetch items from an xml file.
My XML
<xml>
<item>
<title>Title 1</title>
<description>Description 1</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
<item>
<title>Title 2</title>
<description>Description 2</description>
<duration>55:00</duration>
<published>28/01/2011</published>
</item>
</xml>
background.html
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new items (30s)
var req; // request object
var unreadCount = 0; // how many unread items we have
var items; // all currently fetched items
getItems();
//setInterval(getItems, fetchFreq);
function getItems(){
req = new XMLHttpRequest();
req.open("GET", "http://urltoxml.com/xmlfile.xml", false);
req.onload = processItems;
req.send();
}
function processItems(){
xmlDoc = req.responseXML;
items = xmlDoc.getElementsByTagName("item");
unreadCount += items.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
items = xmlDoc.concat(items);
}
</script>
</head>
</html>
I don't know how to get the fetched items from the background.html and displayed onto the popup.html ?
popup.html
<html>
<head>
<link rel="stylesheet" href="popup.css" />
<script src="util.js"></script>
<script>
var bg; // background page
// timeline attributes
var timeline;
var template;
var title;
var link;
var description;
onload = setTimeout(init, 0); // workaround for http://crbug.com/24467
// initialize timeline template
function init() {
chrome.browserAction.setBadgeText({text: ''});
bg = chrome.extension.getBackgroundPage();
bg.unreadCount = 0;
timeline = document.getElementById('timeline');
template = xpath('//ol[#id="template"]/li', document);
title = xpath('//div[#class="text"]/span', title);
content = xpath('//div[#class="text"]/span', template);
update();
}
function update(){
// how to do this ?
// See Chritter example below with JSON,
// except i want to it with xml ?
}
</script>
</head>
<body>
<div id="body">
<ol id="timeline" />
</div>
<ol id="template">
<li>
<div class="text">
<a></a>
<span></span>
</div>
<div class="clear"></div>
</li>
</ol>
</body>
</html>
The way the Chritter extension does it only seems to work with JSON. Here is how they do it:
// update display
function update() {
var user;
var url;
var item;
for (var i in bg.tweets) {
user = bg.tweets[i].user;
url = 'http://twitter.com/' + user.screen_name;
// thumbnail
link.title = user.name;
link.href = openInNewTab(url);
image.src = user.profile_image_url;
image.alt = user.name;
// text
author.href = openInNewTab(url);
author.innerHTML = user.name;
content.innerHTML = linkify(bg.tweets[i].text);
// copy node and update
item = template.cloneNode(true);
timeline.appendChild(item);
}
}
Chritter background.html
<html>
<head>
<script type="text/javascript">
var fetchFreq = 30000; // how often we fetch new tweets (30s)
var req; // request object
var unreadCount = 0; // how many unread tweets we have
var tweets; // all currently fetched tweets
getTweets();
setInterval(getTweets, fetchFreq);
// fetch timeline from server
function getTweets() {
req = new XMLHttpRequest();
req.open('GET', 'http://twitter.com/statuses/public_timeline.json');
req.onload = processTweets;
req.send();
}
// process new batch of tweets
function processTweets() {
var res = JSON.parse(req.responseText);
unreadCount += res.length;
if (unreadCount > 0) {
chrome.browserAction.setBadgeBackgroundColor({
color: [255, 0, 0, 255]
});
chrome.browserAction.setBadgeText({text: '' + unreadCount});
}
tweets = res.concat(tweets);
}
</script>
</head>
</html>
Any help much appreciated! Thanks!
If you want to access items var from a background page then:
var items = chrome.extension.getBackgroundPage().items;
I am not sure what the exact question is, but the general practice is to store the data from background page into localstorage and then access this data from the popup page.
http://www.rajdeepd.com/articles/chrome/localstrg/LocalStorageSample.htm