Skip to content

I built 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.

Notifications You must be signed in to change notification settings

aremuumera/Dom-trace-Debugger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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-debugger

Quick 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, or characterData
  • 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 build

Watch Mode

npm run dev

Project 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 file

Testing in Browser

Method 1: Using npm link (Recommended for development)

  1. Build the library:

    npm run build
  2. Link the package:

    npm link
  3. In your test project:

    npm link dom-trace-debugger
  4. Create 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.)

  1. Install in your project:

    npm install dom-trace-debugger
  2. Use 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

  1. Update package.json with your details:

    {
      "name": "dom-trace-debugger",
      "version": "1.0.0",
      "author": "Your Name <your.email@example.com>",
      "repository": {
        "type": "git",
        "url": "https://github.com/yourusername/dom-trace-debugger.git"
      }
    }
  2. Build the library:

    npm run build
  3. Test 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 adduser

3. Login

npm login

4. Publish

npm publish

For scoped packages (if you use @yourname/dom-trace-debugger):

npm publish --access public

5. Verify

Check your package on npm:

https://www.npmjs.com/package/dom-trace-debugger

6. 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 publish

License

MIT

Contributing

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

About

I built 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.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published