Skip to content

Repository files navigation

FormAutoSave

Version License

A lightweight, dependency-minimal JavaScript library for automatically saving and restoring form data using browser localStorage/sessionStorage. Never lose form data again due to accidental page refreshes, browser crashes, or navigation errors.

Features

  • Automatic Saving - Saves form data as users type with configurable debouncing
  • Smart Restore - Prompts users to restore previously saved data
  • Data Comparison - Visual side-by-side comparison of saved vs. current data
  • Multiple Forms - Supports multiple forms on a single page
  • Security-Aware - Automatically excludes password fields and allows custom exclusions
  • Auto-Expiration - Configurable data expiration (default: 7 days)
  • Status Indicators - Visual feedback for save status
  • Storage Options - Choose between localStorage or sessionStorage
  • Silent Mode - Auto-restore without user prompts
  • Highly Configurable - Extensive options for customization
  • HTML5 Dialog - Modern native dialog elements
  • Zero Dependencies - Pure vanilla JavaScript, no frameworks required

Demo

View Live Demo

Installation

Via NPM (when published)

npm install form-autosave

Via CDN (when published)

<script src="https://cdn.jsdelivr.net/npm/form-autosave@1.0.0/dist/formAutoSave.min.js"></script>

Manual Installation

  1. Download formAutoSave.js
  2. Include it in your HTML:
<script src="path/to/formAutoSave.js"></script>

Quick Start

Basic Usage

<!-- Add the class 'form-autosave' to your form -->
<form class="form-autosave" id="contactForm">
    <input type="text" name="name" placeholder="Your name">
    <input type="email" name="email" placeholder="Your email">
    <textarea name="message"></textarea>
    <button type="submit">Submit</button>
</form>

<!-- Include the script -->
<script src="formAutoSave.js"></script>

That's it! Your form will now automatically save and restore data.

Advanced Configuration

const formAutoSave = new FormAutoSave({
    // CSS selector for forms to auto-save
    formSelector: '.form-autosave',

    // Optional: CSS selector for a global status element
    statusSelector: '#statusbar',

    // Prefix for localStorage keys
    storagePrefix: 'form_autosave_',

    // Attribute to exclude specific fields
    excludeAttribute: 'data-no-autosave',

    // Debounce delay in milliseconds
    debounceDelay: 500,

    // Maximum age of saved data (in milliseconds)
    maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days

    // Use sessionStorage instead of localStorage
    useSessionStorage: false,

    // Auto-restore without prompting
    useSilentMode: false,

    // Hide save status notifications
    hideNotifications: false,

    // Callbacks
    onSave: (formId, data) => console.log('Form saved:', formId),
    onRestore: (formId, data) => console.log('Form restored:', formId),
    onClear: (formId) => console.log('Form cleared:', formId)
});

Usage Examples

Excluding Specific Fields

<!-- Exclude sensitive fields from auto-save -->
<form class="form-autosave">
    <input type="text" name="username">

    <!-- This field won't be saved -->
    <input type="password" name="password" data-no-autosave>

    <!-- This field won't be saved either -->
    <input type="text" name="otp" data-no-autosave>

    <button type="submit">Login</button>
</form>

Excluding Entire Forms

<!-- This form won't use auto-save -->
<form data-no-autosave>
    <input type="text" name="sensitive_data">
    <button type="submit">Submit</button>
</form>

Global Status Indicator

<!-- Status will be shown here instead of individual form indicators -->
<div id="statusbar"></div>

<form class="form-autosave">
    <!-- form fields -->
</form>

<script>
const formAutoSave = new FormAutoSave({
    statusSelector: '#statusbar'
});
</script>

Silent Mode (Auto-Restore)

// Automatically restore saved data without prompting
const formAutoSave = new FormAutoSave({
    useSilentMode: true,
    showNotifications: false
});

API Reference

Configuration Options

Option Type Default Description
formSelector String '.form-autosave' CSS selector for forms to enable auto-save
statusSelector String null CSS selector for global status element
storagePrefix String 'form_autosave_' Prefix for storage keys
excludeAttribute String 'data-no-autosave' Attribute to exclude fields/forms
debounceDelay Number 500 Debounce delay in milliseconds
maxAge Number 604800000 Max age of saved data (7 days default)
useSessionStorage Boolean false Use sessionStorage instead of localStorage
useSilentMode Boolean false Auto-restore without prompting
showNotifications Boolean true Show save status indicators
onSave Function null Callback when form is saved
onRestore Function null Callback when form is restored
onClear Function null Callback when form data is cleared

API Convention

Methods and properties prefixed with _ are private and should not be used directly. Only use the public API methods documented below.

Public Methods

getFormIdentifer(form)

Manually get the form identifier for a specific form.

formAutoSave.getFormIdentifier(form);

getStorageInfo()

Get information about storage usage.

const info = formAutoSave.getStorageInfo();
console.log(info);
// { formCount: 3, totalSize: 2048, totalSizeKB: '2.00' }

export(formId)

Export saved data for a specific form.

const data = formAutoSave.export('contactForm');
console.log(data);

import(formId, data)

Import data for a specific form.

formAutoSave.import('contactForm', savedData);

getForm(formId)

Manually get the form data for a specific form.

formAutoSave.getForm('contactForm');

saveForm(formId)

Manually trigger a save for a specific form.

formAutoSave.saveForm('contactForm');

saveAllForms()

Manually trigger a save for all forms.

formAutoSave.saveAllForms();

clearForm(formId)

Manually trigger a clear for a specific form.

formAutoSave.clearForm('contactForm');

clearAllForms()

Clear all saved form data from storage.

formAutoSave.clearAllForms();

Browser Support

  • Chrome/Edge (latest)
  • Firefox (latest)
  • Safari (latest)
  • Opera (latest)
  • IE 11+ (with polyfills for Event constructor)

Security Considerations

  • Password fields are automatically excluded
  • File input fields are automatically excluded
  • Use data-no-autosave attribute for sensitive fields
  • Data is stored in browser's local storage (unencrypted)
  • For sensitive applications, consider using sessionStorage instead
  • Implement server-side validation - never trust client-side data

Performance

  • Debouncing: Prevents excessive saves during rapid typing
  • Minimal DOM manipulation: Efficient event handling
  • Small footprint: ~15KB minified
  • No polling: Event-driven architecture

Troubleshooting

Forms not saving

  1. Ensure form has the correct class: class="form-autosave"
  2. Check that form has an id, name, or action attribute
  3. Check browser console for errors

Data not restoring

  1. Check if data has expired (default: 7 days)
  2. Verify storage isn't full
  3. Ensure same domain/protocol (localStorage is origin-specific)
  4. Check if useSilentMode is enabled

Browser compatibility issues

  1. Test in different browsers
  2. Check console for JavaScript errors
  3. Ensure dependencies are properly loaded

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Changelog

Version 1.0.0 (2026-04-22)

  • Initial release
  • Auto-save functionality
  • Data comparison UI
  • Silent mode
  • Multiple form support
  • Configurable expiration

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

David Herman

Acknowledgments

  • Built with assistance from GitHub Copilot (Claude Sonnet 4.5)
  • Inspired by the need for better form data persistence
  • FontAwesome for beautiful icon library (optional enhancement)
  • HTML5 Dialog specification for native modal support
  • Community feedback and contributions

Support

If you find this project useful, please consider:

  • Starring the repository
  • Reporting bugs
  • Suggesting new features
  • Improving documentation

About

No description, website, or topics provided.

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages