← Script library

Client Scripts

Auto-save Draft Functionality

Periodically save form data automatically to prevent data loss if browser crashes or session expires.

JavaScript
function onLoad() {
  // Configuration
  var autoSaveInterval = 120000;  // Auto-save every 2 minutes (120000ms)
  var storageKey = 'autosave_' + g_form.getTableName() + '_' + g_form.getUniqueValue();

  // Skip auto-save for existing records that are already saved
  // or if user is read-only
  if (!g_form.isNewRecord() && !g_form.isModified()) {
    return;
  }

  // Function to save form data to browser storage
  function saveDraft() {
    // Only save if form has been modified
    if (!g_form.isModified()) {
      return;
    }

    var draftData = {
      timestamp: new Date().toISOString(),
      table: g_form.getTableName(),
      sys_id: g_form.getUniqueValue(),
      fields: {}
    };

    // Get list of fields to save (exclude system fields)
    var fieldsToSave = ['short_description', 'description', 'category', 
                        'subcategory', 'priority', 'urgency', 'impact',
                        'assignment_group', 'assigned_to', 'work_notes'];

    // Save each field value
    fieldsToSave.forEach(function(fieldName) {
      var value = g_form.getValue(fieldName);
      if (value) {
        draftData.fields[fieldName] = value;

        // For reference fields, also save display value
        if (g_form.getField(fieldName) && 
            g_form.getField(fieldName).type === 'reference') {
          draftData.fields[fieldName + '_display'] = g_form.getDisplayValue(fieldName);
        }
      }
    });

    // Save to localStorage
    try {
      localStorage.setItem(storageKey, JSON.stringify(draftData));
      console.log('Draft auto-saved at ' + draftData.timestamp);

      // Optional: Show subtle notification
      g_form.addInfoMessage('Draft saved automatically');
      setTimeout(function() {
        g_form.clearMessages();
      }, 2000);

    } catch (e) {
      console.error('Error saving draft:', e);
      // localStorage might be full or disabled
    }
  }

  // Function to restore draft
  function restoreDraft() {
    try {
      var savedDraft = localStorage.getItem(storageKey);

      if (savedDraft) {
        var draftData = JSON.parse(savedDraft);

        // Check if draft is recent (less than 24 hours old)
        var draftAge = new Date() - new Date(draftData.timestamp);
        var maxAge = 24 * 60 * 60 * 1000;  // 24 hours

        if (draftAge < maxAge) {
          // Ask user if they want to restore
          var draftDate = new Date(draftData.timestamp);
          var message = 'A draft from ' + draftDate.toLocaleString() + 
                       ' was found. Would you like to restore it?';

          if (confirm(message)) {
            // Restore each field
            Object.keys(draftData.fields).forEach(function(fieldName) {
              // Skip display value fields
              if (fieldName.endsWith('_display')) {
                return;
              }

              var value = draftData.fields[fieldName];
              if (value && !g_form.getValue(fieldName)) {
                g_form.setValue(fieldName, value);
              }
            });

            g_form.addInfoMessage('Draft restored successfully');
          }

          // Clean up old draft
          localStorage.removeItem(storageKey);
        } else {
          // Remove expired draft
          localStorage.removeItem(storageKey);
        }
      }
    } catch (e) {
      console.error('Error restoring draft:', e);
    }
  }

  // Function to clear draft
  function clearDraft() {
    try {
      localStorage.removeItem(storageKey);
      console.log('Draft cleared');
    } catch (e) {
      console.error('Error clearing draft:', e);
    }
  }

  // Restore draft if exists (only for new records)
  if (g_form.isNewRecord()) {
    restoreDraft();
  }

  // Set up auto-save interval
  var autoSaveTimer = setInterval(saveDraft, autoSaveInterval);

  // Save before leaving page
  window.addEventListener('beforeunload', function() {
    saveDraft();
  });

  // Clear draft on successful submit
  g_form.onSubmit(function() {
    clearDraft();
  });

  // Add manual save button
  // g_form.addInfoMessage('<a href="javascript:saveDraft()">Save draft now</a>');

  console.log('Auto-save enabled. Interval: ' + (autoSaveInterval/1000) + ' seconds');
}

How to use it

1. Create an onLoad Client Script on your table 2. Customize autoSaveInterval for your requirements 3. Update fieldsToSave array with fields you want to auto-save 4. Test with browser developer tools localStorage 5. Consider privacy/security implications of local storage 6. Add UI Page or banner to show draft status 7. Test restoration flow thoroughly 8. Clear old drafts periodically to avoid localStorage bloat

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.