限制表单外观和自定义表单处理程序的应用之间的延迟

时间:2018-07-26 14:23:57

标签: javascript google-apps-script google-sheets html-form

我有一个可以工作的HTML表单原型,可以在Google表格的边栏中使用。如果我在运行脚本后等待大约30秒,一切都会正常,否则提交按钮和整个表单就会消失。

Screenshot of the google sheets sheet

如屏幕截图所示,整个过程只是一个简单的HTML表单,带有提交按钮和图片作为按钮。按钮正在运行功能loadSideBar(),单击后我必须等待30秒才能正确使用该表单。否则,整个表单将消失,并且不会在表单中写入任何内容。

是否有机会删除此等待时间?

Code.gs:

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()


function onOpen()
{
  SpreadsheetApp.getUi().createMenu('My Tools')
    .addItem('createTextEntryForm', 'createTextEntryForm')
    .addToUi();

  loadSideBar();
  SpreadsheetApp.getUi().createMenu('My Menu').addItem('loadSidebar', 'loadSideBar').addToUi();  
}


function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow() + 1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }
}

function loadSideBar()
{
  var userInterface=HtmlService.createHtmlOutputFromFile('index');//sidebar for html and formBar for form
  SpreadsheetApp.getUi().showSidebar(userInterface);

 // doPost ();


}

index.html:

<form name="submit-to-google-sheet">
  <input name="email" type="email" placeholder="Email" required>
  <input name="firstName" type="text" placeholder="First Name">
  <input name="lastName" type="text" placeholder="Last Name">
  <BR>
  <BR>
  <button type="submit">Send</button>
</form>

<script src="https://wzrd.in/standalone/formdata-polyfill"></script>
<script src="https://wzrd.in/standalone/promise-polyfill@latest"></script>
<script src="https://wzrd.in/standalone/whatwg-fetch@latest"></script>

<script>
  const scriptURL = 'https://script.google.com/macros/s/AKfycbx0rzbLMsXKQ1C3--qP-wHtcFdfvmOG--y_Qpk0xc43EqtUdSeF/exec'
  const form = document.forms['submit-to-google-sheet']

  form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, { method: 'POST', body: new FormData(form)})
      .then(response => console.log('Success!', response))
      .catch(error => console.error('Error!', error.message))
  })
</script>

0 个答案:

没有答案