Get String Value of Blob Passed to e.parameter in Apps Script - javascript

I'm using this code to get a blob passed to a function:
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
This is the error I get:
Execution failed: TypeError: Can not find getDataAsString function in
the Blob object.'arrayBlob'
How do I get the string value of this blob?
Here is my code:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = userProperties.getProperty('savedArray');
arrayList = JSON.stringify(arrayList);
var arrayBlob = Utilities.newBlob(arrayList);
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
arrayList = JSON.parse(arrayList);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = e.parameter.arrayBlob;
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
I'd like the solution worked with more than one user simultaneous using the script.

Update:
Add a global variable OUTSIDE of any function:
var arrayBlob = Utilities.newBlob("dummy data");
function showList(folderID) {
Code here ....
};
Check that the code has access to the blob:
function submit(e){
Logger.log("arrayBlob.getDataAsString(): " + arrayBlob.getDataAsString());
//More Code . . .
}
This solution eliminates the need of embedding a hidden element in the dialog box with a value of the blob.
You won't need this line:
panel.add(app.createHidden('arrayBlob', arrayBlob));
There are other changes I'd make to the code, but I simply want to show the main issue.
Old Info:
In the function showList(), the method getDataAsString() works on the blob named arrayBlob.
Logger.log("arrayBlob #1 = " + arrayBlob.getDataAsString()); // Here it`s OK
In the function, submit(), the same method does not work.
var arrayBlob = e.parameter.arrayBlob;
In the function showList(), the code is assigning a newBlob to the variable arrayBlob. So arrayBlob is available to have the getDataAsString() method used on it.
var arrayBlob = Utilities.newBlob(arrayList);
In the function, submit(), you are trying to pass the arrayBlob blob variable into the submit() function, and reference it with e.parameter.
If you put a Logger.log() statement in the submit() function.
function submit(e){
Logger.log('e: ' + e);
Logger.log('e.parameter` + e.parameter);
var arrayBlob = e.parameter.arrayBlob;
Those Logger.log statements should show something in them. If there is nothing in e.parameter, then there is nothing for the .getDataAsString() to work on.
It looks like you are putting the arrayBlob into a hidden panel.
panel.add(app.createHidden('arrayBlob', arrayBlob));
But when the object is getting passed to the submit(e) function, the arrayBlob might not be getting put into that object.
So, what I'm saying is, the:
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
Line may be perfectly good, but there is no arrayBlob there to work on. This hasn't fixed your problem, but do you think I'm understanding part of what is going on?

I'm not sure why you are using Blob's here at all, you could simply work with JSON instead.
However, if you have a reason to use Blobs, you can pass the JSON data through your form and create the Blob in your handler, as the modified code below does:
function showList(folderID) {
var folder = DocsList.getFolderById(folderID);
var files = folder.getFiles();
var arrayList = [];
for (var file in files) {
file = files[file];
var thesesName = file.getName();
var thesesId = file.getId();
var thesesDoc = DocumentApp.openById(thesesId);
for (var child = 0; child < thesesDoc.getNumChildren(); child++){
var thesesFirstParagraph = thesesDoc.getChild(child);
var thesesType = thesesFirstParagraph.getText();
if (thesesType != ''){
var newArray = [thesesName, thesesType, thesesId];
arrayList.push(newArray);
break;
}
}
}
arrayList.sort();
var result = UserProperties.getProperty('savedArray');
//get JSON data pass through form.
var arrayBlob = JSON.stringify(arrayList);
var mydoc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setWidth(550).setHeight(450);
var panel = app.createVerticalPanel()
.setId('panel');
//include JSON Data in the form.
panel.add(app.createHidden('arrayBlob', arrayBlob));
var label = app.createLabel("Selecione os itens desejados").setStyleAttribute("fontSize", 18);
app.add(label);
panel.add(app.createHidden('checkbox_total', arrayList.length));
for(var i = 0; i < arrayList.length; i++){
var checkbox = app.createCheckBox().setName('checkbox_isChecked_'+i).setText(arrayList[i][0]);
Logger.log("arrayList[i][0] = " + arrayList[i][0]);
Logger.log("arrayList[i] ====> " + arrayList[i]);
panel.add(checkbox);
}
var handler = app.createServerHandler('submit').addCallbackElement(panel);
panel.add(app.createButton('Submit', handler));
var scroll = app.createScrollPanel().setPixelSize(500, 400);
scroll.add(panel);
app.add(scroll);
mydoc.show(app);
}
function submit(e){
var arrayBlob = Utilities.newBlob(e.parameter.arrayBlob);
Logger.log("arrayBlob #2 = " + arrayBlob.getDataAsString());
// Continues...
}
In the method you were using originally, the Blob itself was never included in the form, you were simply passing the string "Blob" around.
This is because the function createHidden(name, value); expects two strings as parameters, so it calls ".toString()" on the arrayBlob object, which returns the string "Blob".

Related

Put variable name in JSON Array (fetched by an api)

I am very new to Javascript but I will try to put this in convenient way. I am having this api where I am fetching the rank of a crypto (Ripple; currently ranked 7 and is subject to change overtime ), code below:
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
}
Now this is another function for an api where I extract other infos (having 5000+ crytos listed, including ripple)
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRP = data[7].symbol;
// Here instead of [7], I need to put the value extracted from XRPrank above so that whenever the rank is changed I get the latest value on data.[].
If someone could please advise.
In JavaScript there are several ways to achieve what you are looking for. The following is an adaptation of your current code with what I think are the minimal changes that you have to do, 1. use return followed by XRPrank 2. Call myFunction from myXRP and replace the data index by XRPrank.
function myFunction() {
var url = "https://api.coinpaprika.com/v1/coins/xrp-xrp";
var XRPresponse = UrlFetchApp.fetch(url);
var XRPjson = XRPresponse.getContentText();
var XRPdata = JSON.parse(XRPjson);
var XRPrank = XRPdata.rank;
return XRPrank; // add this
}
function myXRP() {
var url = "https://api.coinpaprika.com/v1/tickers";
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var XRPrank = myFunction(); // add this
// var XRP = data[7].symbol; instead of this
var XRP = data[XRPrank].symbol; // use this
}
Resources
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

Google Drive + Script throws permissions error even through I'm owner and granted permission

I'm trying to create a basic script on a 12-hour timer trigger that loops through each of my Google Calendars by their ICAL URL, and downloads the ICAL for a folder on my Google Drive (for backup purposes). It throws this error
"No item with the given ID could be found, or you do not have permission to access it. (line 23, file "Code")" (Line #23 is var folder... )
Running the script does download and save the ICAL file on the first run through the loop (and if I manually pass in each unique ICAL URL one at a time), but the error then terminates the loop. Seeing as how I've authorized access already and am the owner of everything here, I'm not sure what else I need.
var calendarsToSave = [
"https://calendar.google.com/calendar/ical/inXXXXXXX.com/privateXXXX/basic.ics",
"https://calendar.google.com/calendar/ical/XXXXX.com_XXXXXXup.calendar.google.com/private-XXXXXXX/basic.ics"
];
var folder = '123xxxxxxxxv789'; // my gdrive folder
function downloadFile(calendarURL,folder) {
var fileName = "";
var fileSize = 0;
for (var i = 0; i < calendarsToSave.length; i++) {
var calendarURL = calendarsToSave[i];
var response = UrlFetchApp.fetch(calendarURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var folder = DriveApp.getFolderById(folder); // << returns a permissions error thus terminating the for loop
var file = folder.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
} // end for loop
}
Updated: You are also re-initializing a variable that already exists from the parameters and as a global variable so we can remove the parameter if you want to keep the global variable.
We can also move the place where you get the Google Folder object. It stays the same every time so we don't need to retrieve it again.
var calendarsToSave = [
"https://calendar.google.com/calendar/ical/inXXXXXXX.com/privateXXXX/basic.ics",
"https://calendar.google.com/calendar/ical/XXXXX.com_XXXXXXup.calendar.google.com/private-XXXXXXX/basic.ics"
];
var folder = '123xxxxxxxxv789'; // my gdrive folder
function downloadFile(calendarURL) {
var fileName = "";
var fileSize = 0;
var gfolder = DriveApp.getFolderById(folder);
for (var i = 0; i < calendarsToSave.length; i++) {
var calendarURL = calendarsToSave[i];
var response = UrlFetchApp.fetch(calendarURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob()
var file = gfolder.createFile(fileBlob);
fileName = file.getName();
fileSize = file.getSize();
}
var fileInfo = { "rc":rc, "fileName":fileName, "fileSize":fileSize };
return fileInfo;
} // end for loop
}
Let see where that gets us.
Your "folder" variable is outside the function, causing the data to be inaccessible to the "downloadFile" function.
Google apps coding seems to require variables to be in a function to be defined. I would recommend moving both "calendarsToSave" and "folder" to the inside of "downloadFile"
Here is an example that will return your error:
var folder = '1HSFBPfPIsXWvFEb_AalFYalkPwrOAyxD';
function myFunction() {
var folder = DriveApp.getFolderById(folder);
var name = folder.getName();
Logger.log(name);
}
And here is one that will return the file name:
function myFunction() {
var folder = '1HSFBPfPIsXWvFEb_AalFYalkPwrOAyxD';
var folder = DriveApp.getFolderById(folder);
var name = folder.getName();
Logger.log(name);
}

Cannot call method 'push' of undefined when appending JSON Array

Keep getting a error that I can't push a JSON object to a JSON array. Only changes I made was that I this function is in a different file and so I called it as a module.
index.js
var mods = require('../server/api/getUserMods.js');
var usernamePerms = [ 'settings', 'mod1', 'mod2' ]
console.log(mods.getUserMods(usernamePerms));
getUserMods.js
var fs = require('fs');
exports.getUserMods = function(input) {
var umkModules = '../umk_modules/';
var modules = '{"module":[]}';
var moduleParse = JSON.parse(modules);
for (i = 0; i < input.length; i++) {
console.log("Parsing: " + input[i]);
console.log("At: " + umkModules.concat(input[i],"/","module-view.json"));
console.log();
var readModule = JSON.parse(fs.readFileSync(umkModules.concat(input[i],"/","module-view.json"), 'utf8'));
console.log(readModule);
moduleParse['modules'].push(readModule);
};
modules = JSON.stringify(moduleParse);
return modules;
};
The function getUserMods takes a array strings and searches within a specified file path finding a file called module-view.json then appending it to the empty JSON array.
When ran, I get this...
moduleParse['modules'].push(readModule);
moduleParse['module'].push(readModule);
Your property is named module, not modules. And I'm not entirely sure why you'd use JSON when you can simply do:
var moduleParse = {
module:[]
}

JS function is not executed without using Alert box

I am stuck at one point doing JScripting in CRM. I know that problem is with JScript sync/async code execution flow. There is a html control on CRM page which loads some images from DB and displays them. Also, there is an option to manually upload images.
When user uploads an image manually, following function is executed:
function processingImage() {
var list = document.getElementById("image-list");
var imageList = list.getElementsByTagName('img');
var status = false;
for (var i = 0; i < imageList.length; i++) {
var imageSource = imageList[i].src;
var imageName = imageList[i].alt;
var imageTypeSection = imageSource.split(";")[0];
var imageType = imageTypeSection.split(":")[1];
saveImage(imageSource, imageType, "sampleImage-" + imageName);
status = true;
}
if (status) {
//alert("Saved successfully.");
}
return status;
}
You see that there is an alert box of Saved Successfully in this function. The problem is when I display this alert, ONLY then image get saved in DB and it is displayed after page refresh. If I comment out alert box (as in this case) then image does not save into db neither it is showed on the control.
I have no idea how to resolve this issue. Please help.
You can use java script function setTimeout and see if i works or not.
function processingImage() {
var list = document.getElementById("image-list");
var imageList = list.getElementsByTagName('img');
var status = false;
for (var i = 0; i < imageList.length; i++) {
var imageSource = imageList[i].src;
var imageName = imageList[i].alt;
var imageTypeSection = imageSource.split(";")[0];
var imageType = imageTypeSection.split(":")[1];
saveImage(imageSource, imageType, "sampleImage-" + imageName);
status = true;
}
if (status) {
//alert("Saved successfully.");
}
return status;
}
function timeout_init() {
setTimeout('processingImage()', 2000);
}
now call timeout_init instead of processingImage , hopefully this may solve your problem

FF Extension - Not Keeping Global Variable Values

I'm working on a FF extension that in short, loads dynamic images into a sidebar. The ID's that I get are from a JSON response, and are stored in a global variable declared in the same .js file as I intend to use it. My problem is when I try to simulate paging through my results. I load the sidebar using my global variable and everything is ok. When I try to then move on to the next set of images to display using the ID's i've stored in my global variable it failes due to my variable having been completely reset. I'll see if I can give a rough view of my code:
var searchVars = {
'keyword': "",
'totalResults': 0,
'imgIds': [],
'cIds': [],
'curPg': "1",
'dispStartIdx': 0,
'dispEndIdx': 4,
'dispPerPg': 5,
toString: function() {
return this.keyword + ", " +
this.totalResults + ", " +
this.imgIds + ", " +
this.cIds + ", " +
this.curPg + ", " +
this.dispStartIdx + ", " +
this.dispEndIdx + ", " +
this.dispPerPg;
}
};
var corbisquicksearch = {
onSearch: function () {
cqsearch.resetSearch(); //Resets my global variable every search
searchVars.keyword = cqsearch.getSelectedText(); //searchVars is my global variable im having trouble with
cqsearch.extendImageCache();
}
extendImageCache: function() {
var postToURL = 'http://www.agenericurl.com/Search?';
var keyword = searchVars.keyword;
var p = 1; //Page Offset for ID's returned
var size = 200; //Number of ID's returned in the response set
var query = "searchQuery=" + encodeURIComponent("q=" + keyword + "&p= " + p +"&s=" + size);
var request = new XMLHttpRequest();
request.open('post', postToURL + query, true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
alert(1);
if(request.status == 200) {
alert(2);
var responseInJSON = JSON.parse(request.responseText);
searchVars.totalResults = responseInJSON.ResultsCount;
var i = searchVars.imgIds.length;
var lastResult = i + responseInJSON.SearchResultImages.length;
while (i < lastResult) {
searchVars.imgIds[i] = responseInJSON.SearchResultImages[i].ImageId;
searchVars.cIds[i] = responseInJSON.SearchResultImages[i].CorbisId;
i++;
}
cqsearch.loadSidebar();
}
else {
dump("Error loading page\n");
}
}
};
request.send();
},
loadSidebar: function() {
//Initializing Env Variables
var sidebar = document.getElementById("sidebar");
var sidebarDoc = sidebar.contentDocument || document;
var searchInfoBox = sidebarDoc.getElementById("search_info");
var resultsBox = sidebarDoc.getElementById("img_results");
var pagingInfoBox = sidebarDoc.getElementById("paging_info");
//Loading up the search information
var searchInfo = "Displaying Results for <b>{0}<b/><br>Showing <b>{1} - {2}</b> of <b>{3}</b>";
var args = [searchVars.keyword, searchVars.dispStartIdx, searchVars.dispEndIdx, searchVars.totalResults];
var infoLbl = document.createElement("label");
infoLbl.setAttribute("value", cqsearch.strFormat(searchInfo, args));
searchInfoBox.appendChild(infoLbl);
while (resultsBox.firstChild) {
resultsBox.removeChild(resultsBox.firstChild);
}
//Loading up the image results
var i = searchVars.dispPerPg * (searchVars.curPg - 1);
var lastDisplayed = (searchVars.curPg * searchVars.dispPerPg) - 1;
alert("length" + searchVars.toString());
while (i <= lastDisplayed) {
var imageID = searchVars.imgIds[i];
var cID = searchVars.cIds[i];
var imgSrc = cqsearch.createMediaUrlParams(imageID, 'thumb', cID, false).url; //thumb, 170, hover
var img = document.createElement("image");
img.setAttribute("src", imgSrc);
alert(imgSrc);
img.setAttribute("class", "img");
var idDelimiter = "_image";
var id = cID + idDelimiter;
img.id = id;
img.addEventListener("click", function () {
cqsearch.openEnlargementPage(this.id.substring(0, this.id.indexOf(idDelimiter)));
}, false);
var imgBox = document.createElement("box");
imgBox.setAttribute("class", "imgContainer");
imgBox.appendChild(img);
resultsBox.appendChild(imgBox);
i++;
}
//Loading up paging info and functionality
var prevBtn = document.createElement("button");
prevBtn.setAttribute("label", "Previous");
prevBtn.setAttribute("oncommand", "cqsearch.prevPage()");
var nextBtn = document.createElement("button");
nextBtn.setAttribute("label", "Next");
nextBtn.setAttribute("oncommand", "cqsearch.nextPage()");
pagingInfoBox.appendChild(prevBtn);
pagingInfoBox.appendChild(nextBtn);
},
nextPage: function() {
searchVars.curPg++;
alert(searchVars.imgIds);
cqsearch.loadSidebar();
},
};
I realize its a lot of code, and I didn't post every function I have, and no, this specific URL does not work. Everything not included works fine, and does exactly what its supposed too, and nothing more which is why I left it out. But if anyone could shed some light on why my global variable is being cleared between my initial load of the sidebar, and when I click to go to the next page, I would greatly appreciate it.
If you need me to add something or clarify something please let me know and I will do so! I will probably end up sliming this code down and removing irrelevant parts.
Thanks!
If you simply want a place to store some global variables for a session, then a JavaScript Module would probably work.
Would you be able to use the client side storage to store the global variable? you will then, not lose it on page loads or refresh. You could either use this to debug and see if you are getting a page refresh because sometimes extensions are fickle and you don't even notice the refresh, but if you store the variable as a key value pair in web storage you might get past this.
localStorage.setItem('imgId', '5');
to set your key/value pair
localStorage.getItem('imgId');
to retrieve your key/value pair
Then you can set a new local storage for each series of pictures that has been displayed to the client based on the last number that is set in local storage.

Categories

Resources