Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: A Clipboard History Tool

Build a clipboard history utility in Electron: poll the clipboard, deduplicate and limit entries, hide sensitive copies, search history, and paste back through a global shortcut and a tray icon.

A clipboard manager is the classic "only a desktop app can do this" project. It runs in the background, lives in the system tray, watches what you copy, and brings it back with a global keyboard shortcut. It is also a good test of judgement, because it handles sensitive data constantly: passwords copied from a password manager must not end up in a plain list on disk.

You will plan the architecture, then build and run the core: the history engine with deduplication, size limits, search, pinning and privacy rules. The Electron parts (tray, shortcut, clipboard polling) are shown as read-only code, since they need a real desktop.

How it works

flowchart LR
  A["Poll clipboard every 500 ms"] --> B{"Changed?"}
  B -- no --> A
  B -- yes --> C["Privacy filter"]
  C -- sensitive --> A
  C -- ok --> D["History engine: dedupe, limit, persist"]
  D --> E["Tray menu and picker window"]
  F["Global shortcut"] --> E
  E --> G["Write chosen item back to clipboard"]

Electron has no "clipboard changed" event on every platform, so the app polls cheaply and compares.

The main process skeleton

JavaScript
// main.js
import { app, BrowserWindow, clipboard, globalShortcut, Tray, Menu, nativeImage } from 'electron';
import { History } from './history.js';

let tray, picker, history, lastText = '';

app.whenReady().then(() => {
  app.dock?.hide();                              // macOS: no Dock icon for a tray app
  history = new History({ max: 100 });

  tray = new Tray(nativeImage.createFromPath('assets/trayTemplate.png'));
  tray.setToolTip('Clipboard History');
  rebuildMenu();

  setInterval(() => {
    const text = clipboard.readText();
    if (text && text !== lastText) {
      lastText = text;
      if (history.add(text)) rebuildMenu();
    }
  }, 500);

  globalShortcut.register('CommandOrControl+Shift+V', showPicker);
});

app.on('will-quit', () => globalShortcut.unregisterAll());
app.on('window-all-closed', (e) => e.preventDefault());   // keep running in the tray

function rebuildMenu() {
  tray.setContextMenu(Menu.buildFromTemplate([
    ...history.items().slice(0, 10).map((item) => ({
      label: item.preview,
      click: () => { clipboard.writeText(item.text); lastText = item.text; },
    })),
    { type: 'separator' },
    { label: 'Clear history', click: () => { history.clear(); rebuildMenu(); } },
    { role: 'quit' },
  ]));
}

Three details worth noticing: window-all-closed is prevented so closing the picker does not quit the app; will-quit unregisters the global shortcut (it is system-wide and would otherwise linger); and lastText is updated when we write back, so our own paste does not create a duplicate entry.

The history engine

All the interesting rules are plain JavaScript, so we can run and test them. The engine:

  • Deduplicates: copying the same text again moves it to the top instead of adding a second entry.
  • Limits the number of entries and the size of each one.
  • Never stores sensitive-looking text such as things that resemble passwords or card numbers.
  • Supports pinning (pinned items survive the limit and clearing) and search.
Node.js The History engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the results line by line. The duplicate hello world moved to the top rather than being stored twice, the password-shaped string and the valid card number were skipped, the limit of four evicted the oldest unpinned item, and clear() kept the pinned one.

Privacy is the real feature

Clipboard managers are powerful and therefore trusted with secrets. Rules for building one responsibly:

  1. Skip what password managers mark. On macOS they set the pasteboard type org.nspasteboard.ConcealedType; on Windows the format ExcludeClipboardContentFromMonitorProcessing. Check clipboard.availableFormats() and skip those entries.
  2. Skip sensitive shapes as above. This is a heuristic, so also give users a "pause" toggle and an app-exclusion list.
  3. Persist carefully. Keep history in memory by default. If you save it, encrypt with a key from safeStorage (Safe Storage and Fuses), and expire entries after a few days.
  4. Be transparent. Show a tray state when monitoring is paused, and make "Clear history" one click.
  5. Never send clipboard contents over the network without explicit user action.

Global shortcuts and the picker

globalShortcut.register works even when your app has no focus, but it can fail if another app owns that combination. Check the return value and give users a way to rebind:

JavaScript
const ok = globalShortcut.register('CommandOrControl+Shift+V', showPicker);
if (!ok) logger.warn('shortcut already taken');

The picker is a small, frameless, always-on-top window shown near the cursor and hidden when it loses focus:

JavaScript
function showPicker() {
  picker ??= new BrowserWindow({
    width: 420, height: 360, frame: false, alwaysOnTop: true, skipTaskbar: true,
    show: false, resizable: false,
    webPreferences: { preload: join(__dirname, 'preload.js'), sandbox: true },
  });
  picker.on('blur', () => picker.hide());
  picker.loadFile('picker.html');
  picker.once('ready-to-show', () => picker.show());
}

Selecting an item writes it to the clipboard. Simulating the actual "paste" keystroke into another app needs OS accessibility permissions and a native helper, so most tools stop at "put it on the clipboard".

Fuzzy search for the picker

A history of a hundred items benefits from forgiving search: typing sqlus should find SELECT * FROM users. A tiny subsequence matcher with scoring does the job.

Node.js Subsequence search with ranking

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Test the engine

The history class has no Electron dependency, so its tests are plain (Testing Electron Apps). Cases worth writing: duplicate moves to top, limit evicts oldest unpinned, pinned survive clear, card numbers rejected, ordinary text with digits accepted.

Extend it

  • Support images: store a small thumbnail and the PNG on disk, show previews in the picker.
  • Per-app exclusion list using the frontmost-app name from a native helper.
  • Sync between devices only with end-to-end encryption and explicit opt-in.
  • Auto-start at login with app.setLoginItemSettings({ openAtLogin: true }).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the main process update lastText when writing an item back?

    Polling compares against lastText. Updating it on our own write prevents a duplicate entry loop.
  2. 2. What should happen when the same text is copied twice?

    Deduplication keeps the list useful. Moving the entry to the top reflects recency.
  3. 3. Why unregister global shortcuts in will-quit?

    Global shortcuts belong to the OS session, not a window. Releasing them is polite and avoids stale bindings.
  4. 4. Which approach is best for password-manager copies?

    Respect the concealed-content markers and add heuristics; sensitive copies should never reach the history.

Summary

  • A tray app polls the clipboard cheaply, filters, stores and re-offers items through a tray menu and a global shortcut.
  • Keep the rules (dedupe, limits, pinning, search, privacy filters) in a plain testable class.
  • Privacy is the main feature: skip concealed and sensitive-looking copies, persist encrypted or not at all, make clearing easy.
  • Keep the app alive with window-all-closed prevented, and release shortcuts on quit.

Next: Project: A File Organizer with Watching