Sujay Phadke Sujay Phadke - 1 month ago 21
Javascript Question

Unexpected behaviour with PropertiesServices in Google Apps Script

I am trying to implement a GAS script which has a client and server side. I wanted "progress" information from the server to be read on the client side. Since global variables in GAS are only context-global (reset with every invocation), I was told you use 'Properties'. If I understand correctly, shouldn't a 'Property' set at the server-side retain its value between different host function calls? This is not happening.

This is my script:

Client-side:



<!DOCTYPE html>


<div class="container" style="text-align:center">

<button type="button" onclick="setValue();" id="click1">click first</button>
<button type="button" onclick="getValue();" id="click2">click second</button>

<p id="fname" > 00 </p>

</div>

<script type="text/javascript">


function setValue(){


google.script.run
.withSuccessHandler(helper)
.test();

return;
}

function helper(v){
document.getElementById('fname').innerHTML = v;
}

function getValue(){
google.script.run
.withSuccessHandler(helper2)
.test2();

}

function helper2(v){
document.getElementById('fname').innerHTML = v;
}




GAS Server side:



var userProperties = PropertiesService.getScriptProperties();
//var userProperties = PropertiesService.getUserProperties()

userProperties.setProperty('SearchProgress', 50);

Logger.log('orig value = ' + userProperties.getProperty('SearchProgress'));

function doGet() {

var html = HtmlService.createHtmlOutputFromFile('test')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)

return html;
}

function test(){

userProperties.setProperty('SearchProgress', 60);

var value = userProperties.getProperty('SearchProgress');

Logger.log('set value = ' + value);

return value;
}

function test2(){

//userProperties.setProperty('SearchProgress', 100);

var value = userProperties.getProperty('SearchProgress');
Logger.log('get value = ' + value);

return value;

}


Its a very simple piece of code. The client side will create 2 buttons and a text field. It should fetch the required values from the server side script and display it in the text box.

Press button 1 first, and then button 2.

Expect output:
60
60

Actual output:
60
50

Somehow, when button 2 is pressed, its not returning the value of "60" assigned to the property when button 1 is pressed. I am not able to figure out why.

(Notes: It doesn't matter if the property is declared as 'script' or 'user'. Both give the same result.)

Your help is much appreciated.

Answer

Ok I figured it out :) Line no. 3 in the server side code:

userProperties.setProperty('SearchProgress', 50);

gets executed in every invocation of the script (ie: every time button 1 or 2 are pressed) and hence resets the value to '50'. Removing that global initialization solved the problem.