Obsidian Webhooks & Events
Overview
Complete guide to Obsidian's event system: vault events (create, modify, delete, rename), workspace events (layout, leaf changes, editor state), metadataCache events, DOM events, custom EventRef patterns, and periodic tasks. Every event registration uses this.registerEvent() for automatic cleanup on plugin unload.
Prerequisites
- Working Obsidian plugin with
onload() / onunload() lifecycle
- Understanding of TypeScript event handler signatures
- Familiarity with Obsidian's TFile, TFolder, and WorkspaceLeaf types
Instructions
Step 1: Vault Events — File Lifecycle
Vault events fire when files and folders are created, modified, deleted, or renamed.
import { Plugin, TFile, TFolder, TAbstractFile } from 'obsidian';
export default class EventPlugin extends Plugin {
async onload() {
this.registerEvent(
this.app.vault.on('create', (file: TAbstractFile) => {
if (file instanceof TFile) {
console.log('New file:', file.path);
this.onFileCreated(file);
}
if (file instanceof TFolder) {
console.log('New folder:', file.path);
}
})
);
this.registerEvent(
this.app.vault.on('modify', (file: TAbstractFile) => {
if (file instanceof TFile) {
this.onFileModified(file);
}
})
);
this.registerEvent(
this.app.vault.on('delete', (file: TAbstractFile) => {
if (file instanceof TFile) {
this.removeFromIndex(file.path);
}
})
);
this.registerEvent(
this.app.vault.on('rename', (file: TAbstractFile, oldPath: string) => {
if (file instanceof TFile) {
this.updatePathReferences(oldPath, file.path);
}
})
);
}
}
Note: modify fires on every keystroke during live editing in some configurations. Always debounce if your handler does non-trivial work (see obsidian-rate-limits).
Step 2: Workspace Events — UI State Changes
Workspace events track what the user is looking at and how the UI layout changes.
async onload() {
this.registerEvent(
this.app.workspace.on('active-leaf-change', (leaf) => {
if (leaf) {
const view = leaf.view;
if (view.getViewType() === 'markdown') {
const file = (view as any).file as TFile;
if (file) {
this.onActiveFileChanged(file);
}
}
}
})
);
this.registerEvent(
this.app.workspace.on('file-open', (file: TFile | null) => {
if (file) {
this.trackRecentFile(file);
}
})
);
this.registerEvent(
this...(, {
.();
})
);
.(
...(, {
cursor = editor.();
.(cursor., cursor.);
})
);
.(
...(, {
.();
})
);
...( {
.();
});
}
Step 3: MetadataCache Events — Content Indexing
The metadataCache parses frontmatter, links, tags, and headings in the background. These events fire when parsing completes.
async onload() {
this.registerEvent(
this.app.metadataCache.on('changed', (file: TFile, data: string, cache: CachedMetadata) => {
const tags = cache.tags?.map(t => t.tag) ?? [];
const links = cache.links?.map(l => l.link) ?? [];
this.updateFileIndex(file.path, { tags, links });
})
);
this.registerEvent(
this.app.metadataCache.on('resolved', () => {
console.log('Metadata cache fully resolved — safe to query all files');
this.buildFullIndex();
})
);
}
() {
files = ...();
( file files) {
cache = ...(file);
(cache) {
.(file., {
: cache.?.( t.) ?? [],
: cache.?.( l.) ?? [],
: cache.?.( h.) ?? [],
: cache.,
});
}
}
}
The resolved event is critical for plugins that build indexes — querying metadataCache before it fires returns incomplete data.
Step 4: DOM Events with registerDomEvent
For custom UI elements, use registerDomEvent instead of raw addEventListener. Obsidian auto-removes these on plugin unload.
async onload() {
const button = this.addStatusBarItem();
button.setText('Click me');
this.registerDomEvent(button, 'click', (evt: MouseEvent) => {
new Notice('Status bar clicked!');
});
this.registerDomEvent(document, 'keydown', (evt: KeyboardEvent) => {
if (evt.ctrlKey && evt.key === 'q') {
this.toggleFeature();
}
});
const dropZone = createEl('div', { cls: 'my-drop-zone' });
this.registerDomEvent(dropZone, 'dragover', (evt: DragEvent) => {
evt.preventDefault();
dropZone.addClass('drag-active');
});
.(dropZone, , (: ) => {
evt.();
dropZone.();
files = evt.?.;
(files?.) {
.(files);
}
});
}
Step 5: Periodic Tasks with registerInterval
Use registerInterval for timers — they auto-clear on unload. Never use raw setInterval.
async onload() {
this.registerInterval(
window.setInterval(() => {
this.autoSaveDraft();
}, 30_000)
);
this.registerInterval(
window.setInterval(() => {
this.refreshExternalData();
}, 5 * 60_000)
);
}
private draftSaving = false;
private async autoSaveDraft() {
if (this.draftSaving) return;
this.draftSaving = true;
try {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view?.file) {
const content = view.editor.getValue();
await .(view.., content);
}
} {
. = ;
}
}
Step 6: Custom Event Bus for Plugin-Internal Communication
For complex plugins with multiple views or components, create an internal event bus.
import { Events } from 'obsidian';
class PluginEventBus extends Events {
onIndexUpdated(callback: (paths: string[]) => void): EventRef {
return this.on('index-updated', callback);
}
triggerIndexUpdated(paths: string[]) {
this.trigger('index-updated', paths);
}
onSettingsChanged(callback: (settings: PluginSettings) => void): EventRef {
return this.on('settings-changed', callback);
}
triggerSettingsChanged(settings: PluginSettings) {
this.trigger('settings-changed', settings);
}
}
class MyPlugin {
bus = ();
() {
.(
..( {
.?.(paths);
})
);
.(
...(, (file) => {
(file ) {
.(file);
..([file.]);
}
})
);
}
}
Obsidian's Events class is the same base class used by Vault, Workspace, and MetadataCache. Using it for your own bus gives you a consistent pattern with on/off/trigger.
Output
- Vault event handlers for file create, modify, delete, rename
- Workspace event handlers for active leaf, file open, editor changes, layout
- MetadataCache handlers for content parsing and full-vault resolution
- DOM event registration with auto-cleanup
- Periodic tasks with overlap guards
- Custom event bus for internal plugin communication
Error Handling
| Issue | Cause | Solution |
|---|
| Memory leak | Using addEventListener directly | Always use registerDomEvent or registerEvent |
| Stale data in handler | MetadataCache not resolved yet | Wait for resolved event before building index |
| Handler fires before layout | Accessing workspace in onload | Wrap in onLayoutReady callback |
| Handler runs after unload | Raw setInterval not cleared | Use registerInterval exclusively |
| Performance hit from modify | Handler runs on every keystroke | Debounce the handler (500ms is a good default) |
| Null leaf in active-leaf-change | All panes closed | Guard with if (leaf) check |
Examples
File Change Logger
async onload() {
const logEvent = async (action: string, path: string) => {
const today = moment().format('YYYY-MM-DD');
const logPath = `logs/${today}.md`;
const line = `- ${moment().format('HH:mm:ss')} ${action}: ${path}`;
await this.appendOrCreate(logPath, line);
};
this.registerEvent(this.app.vault.on('create', (f) => logEvent('created', f.path)));
this.registerEvent(this.app.vault.on('delete', (f) => logEvent('deleted', f.path)));
this.(...(, (, f.)));
}
Tag Watcher — React to Frontmatter Tag Changes
private tagCache = new Map<string, string[]>();
async onload() {
this.registerEvent(
this.app.metadataCache.on('changed', (file, data, cache) => {
const newTags = cache.frontmatter?.tags ?? [];
const oldTags = this.tagCache.get(file.path) ?? [];
const added = newTags.filter((t: string) => !oldTags.includes(t));
const removed = oldTags.filter(t => !newTags.includes(t));
if (added.length || removed.length) {
this.onTagsChanged(file, added, removed);
}
this.tagCache.set(file.path, [...newTags]);
})
);
}
Resources
Next Steps
For throttling and debouncing these events under load, see obsidian-rate-limits. For production readiness, see obsidian-prod-checklist.