Close sidebar then process form submission

2019-07-20 18:53发布

In my Google Spreadsheet, the user can click a custom menu item that brings up an HTML form in the sidebar so they can enter data. The function that processes that form data takes ~25 seconds to complete. Is it possible to close the sidebar THEN process the form data? It's annoying for the user to have part of the screen blocked for half a minute while the script finishes.

Currently I'm calling this function from <form onSubmit="handleFormSubmit(this)"> and as expected the sidebar only closes after the script is finished:

function handleFormSubmit(formObject) {
  google.script.run.withSuccessHandler(google.script.close).processForm(formObject)
  }

Edit I tried @Jack_Brown's strategy of adding a sleep delay and unfortunately "setTimeout" is not available in Apps Script. Also, I don't think the "async" function declaration is available in Apps Script either. enter image description here

1条回答
家丑人穷心不美
2楼-- · 2019-07-20 19:34

You can call google.script.host.close() right after you call google.script.run.processForm(formObject) to close your sidebar. As mentioned here,

google.script.run is asynchronous client-side JavaScript API

Which, means javascript on the client side doesn't wait for the execution to be over before proceeding to the next line in the code. Hence, you can call google.script.host.close() right after the run API. Like so

function handleFormSubmit(formObject) {
  google.script.run.processForm(formObject)
  google.script.host.close()
  }

Since you are closing the client side prematurely, you dont need a successHandler.
Note: However, you will get no notification if the run fails!

Edit: The call to the google.script.host.close() right after the call to run, seems to affect the asynchronous call. However, adding delay allows it to complete the API call before closing the sidebar. The below function sleeps for 2 seconds before closing the sidebar.

function handleFormSubmit(formObject) {
    google.script.run.processForm(formObject)
    setTimeout(google.script.host.close, 2000)
  }

Reference:
setTimeout()

查看更多
登录 后发表回答