The safest way is to pass the needed data to the HTML directly. If you use properties or cache service it can get complex or fail under multiple simultaneous users.
There are many techniques to pass an initial object from the server [.gs] to the client [.html].
Using HtmlTemplate, you may do:
//.gs file
function doGet[] {
var htmlTemplate = HtmlService.createTemplateFromFile['template-client'];
htmlTemplate.dataFromServerTemplate = { first: "hello", last: "world" };
var htmlOutput = htmlTemplate.evaluate[].setSandboxMode[HtmlService.SandboxMode.IFRAME]
.setTitle['sample'];
return htmlOutput;
}
and in your template-client.html file:
var data = ; //Stores the data directly in the javascript code
// sample usage
function initialize[] {
document.getElementById["myTitle"].innerText = data.first + " - " + data.last;
//or use jquery: $["#myTitle"].text[data.first + " - " + data.last];
}
// use onload or use jquery to call your initialization after the document loads
window.onload = initialize;
It is also possible to do it without using templating, by appending a hidden div to an HtmlOutput:
//.gs file:
function appendDataToHtmlOutput[data, htmlOutput, idData] {
if [!idData]
idData = "mydata_htmlservice";
// data is encoded after stringifying to guarantee a safe string that will never conflict with the html.
// downside: increases the storage size by about 30%. If that is a concern [when passing huge objects] you may use base94
// or even base128 encoding but that requires more code and can have issues, see //stackoverflow.com/questions/6008047/why-dont-people-use-base128
var strAppend = "" + Utilities.base64Encode[JSON.stringify[data]] + "";
return htmlOutput.append[strAppend];
}
// sample usage:
function doGet[] {
var htmlOutput = HtmlService.createHtmlOutputFromFile['html-sample']
.setSandboxMode[HtmlService.SandboxMode.IFRAME]
.setTitle['sample'];
// data can be any [serializable] javascript object.
// if your data is a native value [like a single number] pass an object like {num:myNumber}
var data = { first: "hello", last: "world" };
// appendDataToHtmlOutput modifies the html and returns the same htmlOutput object
return appendDataToHtmlOutput[data, htmlOutput];
}
and in your output-client.html:
/**
* getDataFromHtml
*
* Inputs
* idData: optional. id for the data element. defaults to "mydata_htmlservice"
*
* Returns
* The stored data object
*/
function getDataFromHtml[idData] {
if [!idData]
idData = "mydata_htmlservice";
var dataEncoded = document.getElementById[idData].innerHTML;
var data = JSON.parse[atob[dataEncoded]];
return data;
}
// sample usage of getDataFromHtml
function initialize[] {
var data = getDataFromHtml[];
document.getElementById["myTitle"].innerText = data.first + " - " + data.last;
//or use jquery: $["#myTitle"].text[data.first + " - " + data.last];
}
// use onload or use jquery to call your initialization after the document loads
window.onload = initialize;
Both methods are compared and better explained in this little github I made: //github.com/zmandel/htmlService-get-set-data
How to pass parameters to a web page?
For this purpose a form is created whose values will be transmitted automatically, and in the target page, a script retrieves the values sent.
We have seen how to create a form, we will detail here how to extract the transmitted data.
1] Understanding the format of URL's parameters
Three symbols are used to define a string of parameters to pass:
? concatenates the URL and the string of parameters.
& separates multiple parameters.
= assigns a value to the variable.
Example:
//www.xul.fr/demo.html?login="me"&password="1234"
In this example, we have two parameters, login and password, which are assigned the values "me" and "1234".
2] Values are sent from the form, to the server
You have nothing to do to send the values: all variables and values in a form are sent automatically providing the action of the form is a page to load.
The attribute "name" of each form item will provide the name of the variable and the attribute "value" its value.
...various widgets...
See at the source of the form at bottom.
The GET method appends the data to the URL, while the POST method would transmit them directly.
Sending data without form
To pass parameters to another page or a script without displaying a form [but with a form tag], we use the "hidden" field:
This invisible form will pass to otherpage.html the parameter: varname=12345.
3] Extracting data received from the URL in the page
The location.search attribute contains the chain of parameters, it remains to be analyzed.
Here is the complete code to process data sent:
function processUser[]
{
var parameters = location.search.substring[1].split["&"];
var temp = parameters[0].split["="];
l = unescape[temp[1]];
temp = parameters[1].split["="];
p = unescape[temp[1]];
document.getElementById["log"].innerHTML = l;
document.getElementById["pass"].innerHTML = p;
}
Explanation:
- location.search is the property that holds the list of parameters.
- substring[1] skips the ? symbol and returns the string minus this sign.
- split["&"] splits the string and returns an array whose elements are the parameters.
- this array is assigned to the "parameters" variable. We can now access individual elements by subscripting the array. Parameters[0] is the first element.
- we have to split again the parameter into another small array that holds the name of the variable and the value.
- in this example, we need only for the value, so we subscript the small array to second item, temp[1].
- the unescape function convert special characters.
- we have assigned the l variable with the login value and the p variable with the password.
- the login is written in the log field thanks to the getElementById method.
- and password to the pass field.
4] Updating the page with data received
In this example, I suppose we want to write the data into the page that is loaded with the parameters.
The login variable has been assigned in the previous code.
Two fields have been defined in the page:
The fields are identified by the id property. To fill them with data we have to use the DOM's method getElementById[""] and the innerHTML property.
getElementById["log"].innerHTML = login;
5] Now, testing the script
Fill the fields below and click on the button.
See also
- GET or POST, what method to choose?
- Introduction to forms.
© 2006-2014 Xul.fr