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') ?? []);
Related
Here is the description of my problem.
I have a range of placeholder text and its associated values in a spreadsheet. The placeholder text also exists in a slide presentation which gets replaced using the replacealltext function. However, the colors in the spreadsheet for the values do not change. Please see the examples below.
Google Apps Script:
// Google Sheets
var masterSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = masterSheet.getSheetByName('Monthly Report'); //gets the data from the active pubfile
var range = sheet.getRange('S1:T110');
var data = range.getValues();
var titleName = sheet.getRange('AA14:AA14').getValues().toString();
data.shift(); //removes the headers in the sheets
// Creating the new slide
var spreadsheetID = SpreadsheetApp.getActiveSpreadsheet().getId(); //Ensure Code is applied to active Pubfile
var spreadsheetFolder = DriveApp.getFileById(spreadsheetID);
var parentFolder = spreadsheetFolder.getParents();
var folderID = parentFolder.next().getId();
var reportTemplate = DriveApp.getFileById('SLIDE ID'); // Gets the report Template
var copiedTemplate = reportTemplate.makeCopy(titleName, DriveApp.getFolderById(folderID)); //Makes a copy of the orginal and saves it in the specified folder
var newPresoID = copiedTemplate.getId();
var skeleton = SlidesApp.openById(newPresoID); //opens the new template presentation
var slides = skeleton.getSlides(); //calls the new slides
return newSlide1();
function newSlide1() {
var slide1new = slides[0]; // defining the location of the new slide 1
data.forEach(function (row) {
var templateVariable = row[0]; // First column contains variable names
var templateValue = row[1]; // Second column contains values
slide1new.replaceAllText(templateVariable, templateValue); //replaces all the text that matches the placeholders
slide1new.
});
As you can see, this code just replaces the value but does not bring in the source formatting.
Here are snapshots of the original spreadsheet data and the slides:
Source Data
Destination Slide with Placeholders
Current Result
Desired Result
Please suggest a way to fix this issue. Thank you!
Here is an example of applying the colors of a spreadsheet cell to the table cells of a slide.
My spreadsheet looks like this.
My slide looks like this.
Code.gs
function myFunction() {
try {
let spread = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxxxxx");
let sheet = spread.getSheetByName("Sheet1");
let range = sheet.getRange(2,1,sheet.getLastRow()-1,2);
let values = range.getDisplayValues();
let colors = range.getFontColors();
let present = SlidesApp.getActivePresentation();
let slide = present.getSlides()[0];
let table = slide.getTables()[0];
for( let i=0; i<table.getNumRows(); i++ ) {
let row = table.getRow(i);
for( let j=1; j<row.getNumCells(); j++ ) {
let text = row.getCell(j).getText();
values.some( (value,k) => {
let l = text.replaceAllText(value[0],value[1]);
if( l > 0 ) {
text.getTextStyle().setForegroundColor(colors[k][1]);
return true;
}
return false;
}
);
}
}
}
catch(err) {
console.log(err);
}
}
And the final results look like this.
Reference
TableCell
Array.some()
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);
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;
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)
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);
}
}
}