Saturday, February 11, 2017

Jump to other page on google apps script

We have made a web app in previous posts:  (Hello WorldUse variables in html page, With google spreadsheet). But you would realize that, even if you make 2 or more html pages, you can not easily move to another html page in Google apps script.

In the first place, only one URL is generated for all html pages published for the web app. You can not use the URL simply to link to another page of the web app.

But according to this post in stackoverflaw: http://stackoverflow.com/questions/15668119/linking-to-another-html-page-in-google-apps-script, you can move to another page using google apps script if you can change the doGet() function a bit.

1. Make two html files "page1" and "page2".


page1:
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>Page 1</h1>
    <?var url = getScriptUrl();?><a href='<?=url?>?page=page2'>Link to page2</a>
  </body>
</html>

page2:
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1>Page 2</h1>
    <?var url = getScriptUrl();?><a href='<?=url?>?page=page1'>Link to page1</a>
  </body>
</html>

2. Change the doGet() function as follows: (please note this code was cited from stackoverflow)

For copy and paste:
/**
 * Get "home page", or a requested page.
 * Expects a 'page' parameter in querystring.
 *
 * @param {event} e Event passed to doGet, with querystring
 * @returns {String/html} Html to be served
 */
function doGet(e) {
  Logger.log( Utilities.jsonStringify(e) );
  if (!e.parameter.page) {
    // When no specific page requested, return "home page"
    return HtmlService.createTemplateFromFile('page1').evaluate();
  }
  // else, use page parameter to pick an html file from the script
  return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
}
/**
 * Get the URL for the Google Apps Script running as a WebApp.
 */
function getScriptUrl() {
 var url = ScriptApp.getService().getUrl();
 return url;
}
3. Check your web app. You will see a link was added that allows you to jump to other pages.

Note: if you don't write <base target="_top"> tag on the html pages, your URL will not be changed prorerly.

If you use script to change the page:

Move to  Page2:
<?var url = getScriptUrl();?>window.top.location.href = '<?!=url?>?page=page2';

Move to  Page1:
<?var url = getScriptUrl();?>window.top.location.href = '<?!=url?>?page=page1';