javascripthtmlgoogle-apps-scriptcustom-url

Redirect after processing a POST request in Apps Script


I have had an issue with getting the google scripts page to redirect back towards my custom URL. The script currently executes but I cant get it to redirect back to its previous page after it is finished executing.

Heres the script.gs code:

function doPost(e) {

  try {
    Logger.log(e); // the Google Script version of console.log see: Class Logger
    record_data(e);

    // shorter name for form data
    var mailData = e.parameters;
    var name= String(mailData.name);
    var message= String(mailData.message);
    var email= String(mailData.email);
    var all= ("Name: "+name+"\nReply address: "+email+"\nMessage: "+message);


    // determine recepient of the email
    // if you have your email uncommented above, it uses that `TO_ADDRESS`
    // otherwise, it defaults to the email provided by the form's data attribute
    var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS :     mailData.formGoogleSendEmail;

    MailApp.sendEmail({
        to: String(sendEmailTo),
        subject: String(mailData.subject),
        replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
        body: String(all)
    });    
    doGet();
    return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
  } catch(error) { // if error return this
    Logger.log(error);
    return ContentService
        .createTextOutput(JSON.stringify({"result":"error", "error": error}))
        .setMimeType(ContentService.MimeType.JSON);
  }
}  

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

Here is my HTML code:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="refresh" content="2;url=xxxxxxxxxx.com" />
    <base target="_top">
  </head>
  <body>
    Click <a href="xxxxxxxxxx.com">here</a> to go back.
  </body>
</html>

What would be the best way to make the script open the index.html page so I could easily redirect back to the custom URL?


Solution

  • Here's a working example of redirecting after processing a POST request.

    Code.gs

    var REDIRECT_URL = "http://www.stackoverflow.com";
    
    function doPost(e) {
      Logger.log("POST request");
      Logger.log(e)
      return redirect();
    }
    
    function doGet() {
      Logger.log("GET request");
      var template = HtmlService.createTemplateFromFile("form");
      template.url = ScriptApp.getService().getUrl();
      return template.evaluate();
    }
    
    function redirect() {
      return HtmlService.createHtmlOutput(
        "<script>window.top.location.href=\"" + REDIRECT_URL + "\";</script>"
      ); 
    }
    

    form.html

    <!DOCTYPE html>
    <html>
      <head>
        <base target="_top">
      </head>
      <body>
          <form action="<?= url ?>" method="post">
            <input type="text" name="test_field" value="test data">
            <button type="submit">Submit form</button>
          </form>
      </body>
    </html>
    

    Usage

    When I visit the published web app (i.e. using a GET request), I'm presented with the simple form.

    Submitting that form (i.e. using a POST request), I'm immediately redirected to http://www.stackoverflow.com.

    This output is captured in the script log:

    [18-06-19 10:39:04:731 PDT] POST request
    [18-06-19 10:39:04:732 PDT] {parameter={test_field=test data}, contextPath=, contentLength=20, queryString=, parameters={test_field=[test data]}, postData=FileUpload}
    

    Regarding your code sample, you have:

    doGet();
    return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
    

    That doesn't make sense as you're not doing anything with the results of doGet(). In order to make the doGet() call useful, replace the above with the following:

    return doGet();