Friday 30 August 2019

Adding basic Apps Script and CSS to a web app

This web app project now builds on the foundations we established here and adds the following:
  • A CSS Style Sheet for adjusting layout, colours, font-styles, margins, etc;
  • An event listener to wait for the webpage to fully load before running other functions;
  • An Apps Script function to get the email address of the person visiting the web page.

Screenshot of webpage with CSS styling and email address of visitor
Screenshot of webpage with CSS styling and email address of visitor

CSS Style Sheet
It is good practice to keep the styling of a webpage separate from the main content in its own file, in addition to avoiding in-line styling where individual objects in the HTML are styled on their own (as it makes universal changes cumbersome).

To incorporate our Style Sheet we use the below syntax:
<?!= HtmlService.createHtmlOutputFromFile('filename').getContent(); ?>
From here we can style particular tags and alter a range of cosmetics, for example Heading 1:
h1 {color: #FFFFFF; background: #006577; padding: 15px; margin: 0px;}

Event listener
Before running any other functions we want to ensure the webpage has fully loaded so that it is responsive and avoids any long-running tasks from slowing down the page for the user:
window.addEventListener('load', findUser);
In this example we then run the function findUser after a Success handler has confirmed a successful interaction with the server:
function findUser(){
    google.script.run.withSuccessHandler(onUserSuccess).getUser();
}

getUser.gs
We now have our Apps Script function that can run to simply return the email address of the logged in user accessing the web app:
var theUser = Session.getActiveUser().getEmail();

onUserSuccess
Back in the index.html file the function onUserSuccess grabs the paragraph tags (<p></p>) with the id theUser (from withing the body tags) and populates it with some static text and adds the user's email address in bold (via <strong></strong> tags):
function onUserSuccess(theUser) {
     document.getElementById('theUser').innerHTML = 'Current user email address is: ' +
      '<strong>' + theUser + '</strong>';
}

Web app - CSS & user email.gs

No comments:

Post a Comment