How to put timestamps in local storage? - javascript

Hello I am creating an chrome extension and I am trying to put all my timestamps that a retrieved after visiting a url into an array in local storage but I am having trouble doing so. It continues to update timestamps and i want all my timestamps to stay the same. However it doesnt seem to save anything and i keep receiving this error. Do anyone know how to fix this error or what may be causing it.
function addRow() {
//SavaDataToLocalStorage(data);
//putting dates in array-- works somewhat
//var myDate = data[data.length-1];
//data.length = 0;
const bg = chrome.extension.getBackgroundPage()
Object.keys(bg.get).forEach(function (url) {
// Append product to the table
var data = [];
data = JSON.parse(localStorage.getItem('session')) || [];
// Push the new data (whether it be an object or anything else) onto the array
data.push( Date.now() );
localStorage.setItem('session', JSON.stringify(data));
myDate = data;
//protocol
var arr = url.split("/");
var protocoll = arr[0] + "//" + arr[2];
//inputed data --
browser= "Google Chrome";
protocol = protocoll;
downloads = "example";
description = "example";
//use data or myDate as time
time = myDate;
//have as Date.now()
//will put dates in array and replace it and have var as myDate
// add new row to the table
//1 = in the top
//table.rows.length = the end
//table.rows.length/2+1 = the center
var newRow = table.insertRow(0);
//console.log(table.rows.length) gives length of table
// add cells to the row
var browserCell = newRow.insertCell(0);
var timeCell = newRow.insertCell(1);
var urlCell = newRow.insertCell(2);
var protocolCell = newRow.insertCell(3);
var downloadsCell = newRow.insertCell(4);
var descCell = newRow.insertCell(5);
// add the data to the cells
urlCell.innerHTML = `${url}`;
timeCell.innerHTML = time;
browserCell.innerHTML = browser;
descCell.innerHTML = description;
protocolCell.innerHTML = protocol;
downloadsCell.innerHTML = downloads;
console.log("add row works");
})
}

Fix typo on line:5 date>>>data
var data = [];
data = JSON.parse(localStorage.getItem('session')) || [];
// Push the new data (whether it be an object or anything else) onto the array
data.push( Date.now() );
localStorage.setItem('session', JSON.stringify(data));
myDate = data;
//inputed data
time = myDate;

Related

How do I get arrays mapped in a row in google sheet using JavaScript/Google App script

I have a code that reads two columns (D & H) in multiple sheets and saves them in the array. What I would like to do is to have the data in this array mapped into one row in a stagging sheet but I keep running to an error: running into an error The parameters (number,number,number,null) don't match the method signature for SpreadsheetApp.Spreadsheet.getRangeList. I really every time the sheets are read the data should be appended to the next row. I will appreciate any help in solving the challenge
function combinesheets() {
var folder = DriveApp.getFolderById( Copy_Folder_id)
var filesIterator = folder.getFiles();
var file;
var fileType;
var ssID;
var combinedData = [];
var data;
while(filesIterator.hasNext()){
file = filesIterator.next();
fileType = file.getMimeType();
if(fileType === "application/vnd.google-apps.spreadsheet"){
ssID = file.getId()
data = getDataFromSpreadsheet(ssID);
combinedData = combinedData.concat(data);
} //if ends here
}//while ends here
var ws = SpreadsheetApp.openById(Stage_sheet_id);
var ss = ws.getSheetByName("Project List");
ws.getRangeList(2,1, combinedData.length, combinedData.length [0]).setValues(combinedData) //running into an error on this line- The parameters (number,number,number,null) don't match the method signature for SpreadsheetApp.Spreadsheet.getRangeList.
Logger.log(combinedData)
}
function getDataFromSpreadsheet(ssID){
var ss = SpreadsheetApp.openById(ssID);
var ws = ss.getSheets()[0]
var data = ws.getRange("A11:I" + ws.getLastRow()).getValues();// how do I get the columns I want here (D & H)
Logger.log(data)
}
You are getting the error because the getDataFromSpreadsheet() function does not return its result.
To get the values in columns D and H, omitting blank rows, try this:
const values1 = ws.getRange('D11:D').getValues();
const values2 = ws.getRange('H11:H').getValues();
return values1.map((row, index) => row.concat(values2[index]))
.filter(row => row.join(''));
In combinesheets(), store the data with this:
ss.getRange(2, 1, combinedData.length, combinedData[0].length)
.setValues(combinedData);

How to put timestamps within array in local storage?

Hello I am creating an chrome extension and I am trying to put all my timestamps that a retrieved after visiting a url into an array in local storage but I am having trouble doing so. It continues to update timestamps and i want all my timestamps to stay the same. However it doesnt seem to save anything and i keep receiving this error. Do anyone know how to fix this error or what may be causing it.
function addRow() {
const bg = chrome.extension.getBackgroundPage()
Object.keys(bg.get).forEach(function (url) {
// Append product to the table
var data = [];
data = JSON.parse(localStorage.getItem('session')) || [];
// Push the new data (whether it be an object or anything else) onto the array
data.push( Date.now() );
localStorage.setItem('session', JSON.stringify(data));
myDate = data;
//protocol
var arr = url.split("/");
var protocoll = arr[0] + "//" + arr[2];
//inputed data --
browser= "Google Chrome";
protocol = protocoll;
downloads = "example";
description = "example";
//use data or myDate as time
time = myDate;
//will put dates in array and replace it and have var as myDate
// add new row to the table
//1 = in the top
//table.rows.length = the end
//table.rows.length/2+1 = the center
var newRow = table.insertRow(0);
//console.log(table.rows.length) gives length of table
// add cells to the row
var browserCell = newRow.insertCell(0);
var timeCell = newRow.insertCell(1);
var urlCell = newRow.insertCell(2);
var protocolCell = newRow.insertCell(3);
var downloadsCell = newRow.insertCell(4);
var descCell = newRow.insertCell(5);
// add the data to the cells
urlCell.innerHTML = `${url}`;
timeCell.innerHTML = time;
browserCell.innerHTML = browser;
descCell.innerHTML = description;
protocolCell.innerHTML = protocol;
downloadsCell.innerHTML = downloads;
console.log("add row works");
})
}
"Unexpected token u at position 0" means that you're trying to parse an undefined. Replace
var data = [];
data = JSON.parse(localStorage.getItem('session')) || [];
with
var data = JSON.parse(localStorage.getItem('session') || "[]");
There is a bug in the code.
data = JSON.parse(localStorage.getItem('session')) || [];
should be :
data = JSON.parse(localStorage?.getItem('session') ?? []);

speeding up processing on sheets add-on

I am making an add on that processes content from a Google Sheets doc and returns it (for now) to new sheet in the spreadsheet. The first iteration works but is deadly slow. I think it's because it processes the data sheet one line at a time. So I'm rewriting it to ingest all the data and then process the array it lives in.
Problem is the amount of data appears to be prohibitive. I can see this in Logger output, in execution transcript, and in stackdriver logging; it gets to about line 35 (11 columns) before it runs out of room.
here is the original version (takes an insane amount of time):
'''
var compareDate = selDate;
var bulletin = ss.getSheetByName(reportSheetName);
var responses = ss.getSheetByName("Calendar");
var lastRow = responses.getLastRow(); //get last row of data sheet
var lastBull = bulletin.getLastRow(); //get last row of bulletin sheet
var nextBullRow = lastBull+1;
var nextBullItem = bulletin.getRange(nextBullRow,1);
for(var i = 2; i <= lastRow; i++) {
var row = responses.getRange(i, 1, 1, 11).getValues();
var dateA = new Date((row[0][4]).valueOf());
var eventType = row[0][0].valueOf();
var eventCalDate = new Date(row[0][4].valueOf());
var eventEvent = row[0][3].valueOf();
var eventOpp = row[0][7].valueOf();
var eventLocation = row[0][8].valueOf();
var eventMonth = eventCalDate.getMonth();
var eventDate = eventCalDate.getDate();
var eventYear = eventCalDate.getYear();
var eventShortDate = eventMonth+"/"+eventDate+"/"+eventYear;
var start = new Date(thisWeekSt);
var end = new Date(thisWeekEnd);
/*var masterDate = new Date(compareDate).valueOf();
var thisCat = row[0][3];
var bullItem = row[0][4]; */
var dateMatch = false;
if(dateA > start && dateA < end) {
dateMatch=true;
bulletin.getRange(nextBullRow,1,nextBullRow,6).setFontWeight("normal");
bulletin.getRange(nextBullRow,typeCol).setValue(eventType);
bulletin.getRange(nextBullRow,dateCol).setValue(eventShortDate);
bulletin.getRange(nextBullRow,timeCol).setValue(eventType);
bulletin.getRange(nextBullRow,eventCol).setValue(eventEvent);
bulletin.getRange(nextBullRow,oppCol).setValue(eventOpp);
bulletin.getRange(nextBullRow,locCol).setValue(eventLocation);
nextBullRow++;
Logger.log(bulletin.getRange(nextBullRow-1,6).getValue());
if(bulletin.getRange(nextBullRow-1,6).getValue()=="Hollister") {
bulletin.getRange(nextBullRow-1,1,nextBullRow-1,6).setFontWeight("bold");
Logger.log("boop!");
}
'''
And here's the new version, which doesn't have the digital appetite for all the data;
'''
var compareDate = selDate;
var bulletin = ss.getSheetByName(reportSheetName);
var responses = ss.getSheetByName("Calendar");
var lastRow = responses.getLastRow(); //get last row of data sheet
var lastBull = bulletin.getLastRow(); //get last row of bulletin sheet
var nextBullRow = lastBull+1;
var nextBullItem = bulletin.getRange(nextBullRow,1);
var allData = responses.getRange(2, 1, responses.getLastRow(), 11).getValues();
for(var i = 2; i <= allData.getLastRow(); i++) {
var row = allData.getRange(i, 1, 1, 11).getValues();
Logger.log(row);
'''
Let me know if you want the whole function, I'll edit.
The question is: how can I speed data processing from the sluggish pace it is at currently. (Thanks Cooper!)
In your for loop you are calling getValues each iteration of your loop which looks like the issue. You've already got the data in your call above.
Try:
for(var i = 0; i <= allData.getLastRow(); i++) {
var row = allData[i];
Logger.log(row);
Had the same issue today. My solution was to duplicate the sheet and then work on the copy:
sheet=SpreadsheetApp.getActiveSpreadsheet()
copy=sheet.duplicateActiveSheet()
after duplicating, the copy is the active sheet, so you can directly work on it, e.g. delete rows like that:
sheet.deleteRows(1,2)

When counting information from an array the result is -1 from the actual result

I'm grabbing a spreadsheet from an online report the file is a CSV file I format so is usable by gscript.
So I'm counting everything that's a value over 0 in a loop and using an array. but when displaying the information in one value less...so let's say there are 7 values on the sheet the logger displays 6...I'm super new on this so I'll appreciate any help.
The commission variable is the one with the issue
function start()
{
var startDate = new Date();
var endDate = new Date();
var sMonth = startDate.getMonth()+1; //start day variables
var sDay = startDate.getDate()-3;
var sYear = startDate.getFullYear();
startDate = sMonth+"-"+sDay+"-"+sYear; //concatenate date
endDate = startDate;
var csvUrl = "http://publisherpro.flexoffers.com/Report/Public?gui=9ce2029a-e14c-4548-a1af-0f0e2e8894c8&d1=" +startDate+"&d2="+endDate+ "&t=A&o=CSV"
Logger.log(csvUrl);
var csvContent = UrlFetchApp.fetch(csvUrl).getContentText(); //
Just formating the file to be useable within Google Scripts
var csvData = Utilities.parseCsv(csvContent); // Same as above //Returns a tabular 2D array representation of a CSV string.
var counter = new Array;
var commision = 0;
for (var c = 2; c < csvData.length; c++) {
if (csvData[c][21] > 0)
{
commision++
}
}
Logger.log(commision)
}

How to convert UTC date format provided by SalesForce Api and convert it to local Date and Time format using Google Apps Script

I have looked at various solutions posted i.e. parsing, substrings and splitting and none of them either produce a value or the required value.
The format received via Salesforce API is "2014-08-19T02:26:00.000+0000"
Essentially I would like a custom function that can be used within Google Sheets to convert this date/time format and take daylight saving into consideration
Thank you beforehand
I use a simple function like below :
function parseDate(string) {
var parts = string.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var t = parts[1].split(':');
var refStr = new Date(new Date(parts[0])).toString();// use this to get TZ for daylight savings
var fus = Number(refStr.substr(refStr.indexOf('GMT')+4,2));
return new Date(new Date(parts[0]).setHours(+t[0]+fus,+t[1],0));
}
firstly thank you for everyone's input. By using a combination of the info provided by RobG and Serge insas I revised the script and created one that suited my needs. Please see below, any further advice would be welcome.
/*
The script first has all variables declared.
As the script runs inconjunction with an API query running off single trigger for defined sequential functions where the previous parsed date records are cleared and then re-parsed and runs with loop function for a whole column of data within specified range
*/
function parseDate() {
var source_spreadsheet = SpreadsheetApp.openById("Sheet_Id");
SpreadsheetApp.setActiveSpreadsheet(source_spreadsheet);
var sheet = source_spreadsheet.getSheetByName("Sheet_Tab");
var startRow = 2;
var numRows = 4500;
var startCol = 1;
var numCols = 7;
var dataRange = sheet.getRange(startRow, startCol, numRows, numCols)
sheet.getRange(startRow, startCol + 1, numRows, numCols - 1).clear({contentsOnly: true});
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
var SFConnectDate = row[0];
var DConnected = row[1];
var SFCutoverDate = row[2];
var DInUse = row[3];
var Lat = row[5];
var Long = row[6];
if (SFConnectDate != "" && DConnected == "" && Lat != "" && Long != "") {
var parts = SFConnectDate.split('T');
parts[0] = parts[0].replace(/-/g, '/');
var Fdd = parts[0].split('/');
var AllTime = parts[1].split('.');
var Ftt = AllTime[0].split(':');
var D = new Date(Fdd[0],(Fdd[1]-1),Fdd[2] ,Ftt[0],Ftt[1],Ftt[2]);
var TZ = (D.getTimezoneOffset())/60;
var DConnected = new Date(Fdd[0],(Fdd[1]-1),Fdd[2],(Ftt[0]-TZ),Ftt[1],Ftt[2]);
sheet.getRange(startRow + i, 2).setValue(DConnected);
}
}
}

Categories