dom-trace-debugger
v1.0.0
Published
A small open-source library that watches your DOM for changes, logs detailed mutation info, captures stack traces, and highlights mutated elements visually
Downloads
119
Maintainers
Readme
dom-trace-debugger
A small open-source library that watches your DOM for changes, logs detailed mutation info, captures stack traces, and highlights mutated elements visually. Perfect for debugging unexpected DOM changes in both development and production environments.
Features
- 🔍 Watches DOM mutations - Uses MutationObserver to track all DOM changes
- 📝 Detailed logging - Logs element, mutation type, old/new values, timestamp, and stack trace
- 🎯 Stack trace capture - See exactly where in your code the DOM change originated
- ✨ Visual highlighting - Optional visual outline on mutated elements
- 🌲 Tree-shakable - Only import what you need
- 📦 Zero dependencies - Works in any browser with no external dependencies
- 🔧 TypeScript support - Full type definitions included
- 🚀 Production ready - Works in both dev and production environments
Installation
npm install dom-trace-debuggerQuick Start
import { watchDOM } from "dom-trace-debugger";
// Start watching with visual highlights
watchDOM({ highlight: true });That's it! Now all DOM mutations will be logged to the console with full details.
API
watchDOM(options?)
Starts watching the DOM for mutations.
Parameters:
interface WatchOptions {
highlight?: boolean; // Visual highlight on mutated elements (default: false)
subtree?: boolean; // Watch all descendants (default: true)
childList?: boolean; // Watch for child node changes (default: true)
attributes?: boolean; // Watch for attribute changes (default: true)
characterData?: boolean; // Watch for text content changes (default: true)
attributeOldValue?: boolean; // Record old attribute values (default: true)
characterDataOldValue?: boolean; // Record old text content (default: true)
attributeFilter?: string[]; // Only watch specific attributes (default: [])
}Returns: A function to stop watching
Example:
import { watchDOM } from "dom-trace-debugger";
// Basic usage
const stop = watchDOM();
// With visual highlights
watchDOM({ highlight: true });
// Only watch specific attributes
watchDOM({
attributeFilter: ['class', 'data-id'],
highlight: true
});
// Stop watching
stop();stopWatching()
Stops watching the DOM. You can also use the function returned by watchDOM().
import { watchDOM, stopWatching } from "dom-trace-debugger";
watchDOM();
// ... later
stopWatching();What Gets Logged
For each DOM mutation, you'll see:
- Element - The DOM element that was mutated
- Mutation Type -
attributes,childList, orcharacterData - Old Value - The previous value (if available)
- New Value - The current value
- Timestamp - When the mutation occurred
- Stack Trace - The call stack showing where the mutation originated
Example Console Output
🔍 DOM Mutation: attributes
Element: <div id="myDiv" class="active">
Old Value: inactive
New Value: active
Timestamp: 2024-01-15T10:30:45.123Z
Stack Trace:
at updateClass (app.js:45)
at handleClick (app.js:78)
at HTMLButtonElement.onclick (app.js:120)Advanced Usage
Watch Only Specific Elements
import { watchDOM } from "dom-trace-debugger";
// Watch only a specific element
const element = document.getElementById('myElement');
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
console.log('Mutation:', mutation);
});
});
observer.observe(element, {
childList: true,
attributes: true,
subtree: true
});Custom Logging
import { watchDOM, MutationLog } from "dom-trace-debugger";
// You can access the logging utilities directly
import { logMutation, formatMutationLog } from "dom-trace-debugger";
// Custom mutation handler
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
const log: MutationLog = {
element: mutation.target as Element,
mutationType: mutation.type,
oldValue: mutation.oldValue,
newValue: mutation.target.textContent,
timestamp: Date.now(),
stackTrace: new Error().stack || ''
};
// Send to your logging service
sendToLoggingService(log);
});
});Browser Support
Works in all modern browsers that support MutationObserver:
- Chrome 18+
- Firefox 14+
- Safari 6+
- Edge 12+
- Opera 15+
Development
Build
npm run buildWatch Mode
npm run devProject Structure
dom-trace-debugger/
├── src/
│ ├── index.ts # Main entry point
│ ├── observer.ts # MutationObserver wrapper
│ ├── logger.ts # Logging utilities
│ └── highlighter.ts # Visual highlighting
├── dist/ # Compiled output
├── tsconfig.json # TypeScript configuration
├── package.json # Package configuration
└── README.md # This fileTesting in Browser
Method 1: Using npm link (Recommended for development)
Build the library:
npm run buildLink the package:
npm linkIn your test project:
npm link dom-trace-debuggerCreate a test HTML file:
<!DOCTYPE html> <html> <head> <title>dom-trace-debugger Test</title> </head> <body> <div id="app"> <button id="btn">Click me</button> <div id="content">Initial content</div> </div> <script type="module"> import { watchDOM } from './node_modules/dom-trace-debugger/dist/index.js'; watchDOM({ highlight: true }); // Test mutations document.getElementById('btn').addEventListener('click', () => { document.getElementById('content').textContent = 'Changed!'; document.getElementById('content').setAttribute('data-updated', 'true'); }); </script> </body> </html>
Method 2: Using a bundler (Vite, Webpack, etc.)
Install in your project:
npm install dom-trace-debuggerUse in your code:
import { watchDOM } from 'dom-trace-debugger'; watchDOM({ highlight: true });
Method 3: Direct browser test with CDN (after publishing)
<!DOCTYPE html>
<html>
<head>
<title>dom-trace-debugger Test</title>
</head>
<body>
<div id="app">
<button id="btn">Click me</button>
<div id="content">Initial content</div>
</div>
<script type="module">
import { watchDOM } from 'https://cdn.skypack.dev/dom-trace-debugger';
watchDOM({ highlight: true });
document.getElementById('btn').addEventListener('click', () => {
document.getElementById('content').textContent = 'Changed!';
document.getElementById('content').setAttribute('data-updated', 'true');
});
</script>
</body>
</html>Publishing to npm
1. Prepare for Publishing
Update package.json with your details:
{ "name": "dom-trace-debugger", "version": "1.0.0", "author": "Your Name <[email protected]>", "repository": { "type": "git", "url": "https://github.com/yourusername/dom-trace-debugger.git" } }Build the library:
npm run buildTest locally (optional but recommended):
npm pack # This creates a .tgz file you can test with npm install ./dom-trace-debugger-1.0.0.tgz
2. Create npm Account
If you don't have one:
npm adduser3. Login
npm login4. Publish
npm publishFor scoped packages (if you use @yourname/dom-trace-debugger):
npm publish --access public5. Verify
Check your package on npm:
https://www.npmjs.com/package/dom-trace-debugger6. Update Version
For future updates:
npm version patch # 1.0.0 -> 1.0.1
npm version minor # 1.0.0 -> 1.1.0
npm version major # 1.0.0 -> 2.0.0
npm publishLicense
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
