cdp-use
v0.0.11
Published
Type-safe TypeScript client for Chrome DevTools Protocol
Downloads
289
Maintainers
Readme
CDP-Use TypeScript
A fully type-safe TypeScript client for Chrome DevTools Protocol, ported from the Python CDP-Use library.
✨ Features
- 🔒 100% Type Safe - Zero
anytypes, full TypeScript compilation - 🎯 IntelliSense Support - Complete autocomplete in VS Code and IDEs
- 🚀 Python-Compatible API - Matches the original CDP-Use Python library
- 📦 Auto-Generated - Always up-to-date with latest Chrome DevTools Protocol
- 🔄 Cross-Domain Types - Proper type references like
DOM.NodeId,Runtime.ScriptId - ⚡ High Performance - WebSocket-based with concurrent request support
🚀 Quick Start
Installation
npm install cdp-useBasic Usage
import { CDPClient } from 'cdp-use';
async function example() {
const client = new CDPClient('ws://localhost:9222/devtools/browser/...');
await client.connect();
// Type-safe commands - full autocomplete and type checking!
const targets = await client.send.Target.getTargets();
const page = await client.send.Page.navigate({
url: 'https://example.com'
});
// Type-safe event registration
client.register.Page.onloadEventFired((event) => {
console.log('Page loaded at:', event.timestamp);
});
// Enable domains
await client.send.Page.enable();
await client.send.Runtime.enable();
await client.disconnect();
}📊 What's Generated
This library auto-generates from Chrome DevTools Protocol specifications:
- 53+ CDP Domains - Target, Page, Runtime, DOM, Network, etc.
- 500+ Type-Safe Methods - All with proper parameter and return types
- 1000+ TypeScript Interfaces - Complete type coverage
- Cross-Domain References -
DOM.NodeId,Runtime.RemoteObjectId, etc.
🎮 Examples
See the examples/ folder for complete working examples:
demo.ts- Type safety showcase (no Chrome needed)simple.ts- Basic CDP operations and DOM accessbasic.ts- Event handling and session management
Running Examples
# Type safety demo (no Chrome required)
npm run example:demo
# Real CDP examples (requires Chrome with --remote-debugging-port=9222)
npm run example:simple
npm run example:basic🛠 Development
Prerequisites
Start Chrome with remote debugging:
chrome --remote-debugging-port=9222 --no-first-run --no-default-browser-checkBuild the library:
npm install npm run generate # Downloads latest CDP specs and generates types npm run build # Compiles TypeScript
Regenerating CDP Types
The CDP types are auto-generated from Chrome DevTools Protocol specifications:
# Using task (recommended)
task generate
# Or directly with npm
npm run generateThis downloads the latest protocol definitions and regenerates all TypeScript interfaces.
Version Pinning
By default, the generator downloads the latest CDP specification from the master branch. To pin a specific version, edit src/generator/constants.ts:
// Pin to a specific commit
export const CDP_VERSION = "4b0c3f2e8c5d6a7b9e1f2a3c4d5e6f7a8b9c0d1e";
// Or use master for latest
export const CDP_VERSION = "refs/heads/master";To find specific commits, visit: https://github.com/ChromeDevTools/devtools-protocol/commits/master
Custom Protocol Support
You can add custom CDP domains by placing JSON protocol files in src/custom_protocols/. The generator will automatically include them during type generation.
Example custom protocol (src/custom_protocols/browseruse.json):
{
"domains": [
{
"domain": "BrowserUse",
"description": "Custom domain for BrowserUse events",
"events": [
{
"name": "activeTargetChanged",
"description": "Fired when a target is activated",
"parameters": [
{ "name": "targetId", "$ref": "Target.TargetID" }
]
}
]
}
]
}After adding custom protocols, regenerate types with task generate.
Available Tasks
task generate # Regenerate CDP types from protocol definitions
task build # Build the TypeScript distribution
task dev # Start TypeScript compiler in watch mode
task clean # Clean build artifacts
task format # Format TypeScript code with prettier
task format-json # Format JSON protocol files
task example # Run the demo example
task example:simple # Run the simple example
task test # Run tests
task install # Install dependencies🔥 Type Safety Examples
Method Parameters
// ✅ Correct - TypeScript enforces required parameters
await client.send.Page.navigate({ url: 'https://example.com' });
// ❌ Error - TypeScript catches missing required parameters
await client.send.Page.navigate(); // Error: url parameter requiredReturn Types
const targets = await client.send.Target.getTargets();
// targets.targetInfos is fully typed with autocomplete
const firstTarget = targets.targetInfos[0];
console.log(firstTarget.targetId); // String type, autocomplete availableEvent Handlers
client.register.Runtime.onconsoleAPICalled((event) => {
// event parameter is fully typed
console.log(event.type); // "log" | "warn" | "error" | etc.
console.log(event.args); // Runtime.RemoteObject[]
console.log(event.timestamp); // number
});Cross-Domain Type References
// Types properly reference across domains
const nodeId: DOM.NodeId = await client.send.DOM.querySelector({
selector: 'body'
});
const remoteObject: Runtime.RemoteObject = await client.send.Runtime.evaluate({
expression: 'document.body'
});🌟 API Reference
Main Client
class CDPClient {
constructor(url: string)
async connect(): Promise<void>
async disconnect(): Promise<void>
// Type-safe command sending
send: {
Target: TargetClient,
Page: PageClient,
Runtime: RuntimeClient,
DOM: DOMClient,
// ... all 53+ domains
}
// Type-safe event registration
register: {
Target: TargetClient,
Page: PageClient,
Runtime: RuntimeClient,
DOM: DOMClient,
// ... all 53+ domains
}
}Domain Clients
Each domain provides type-safe methods:
class PageClient {
// Commands
async enable(params?: PageCommands.enableParameters): Promise<{}>
async navigate(params: PageCommands.navigateParameters): Promise<PageCommands.navigateReturns>
async reload(params?: PageCommands.reloadParameters): Promise<{}>
// Event registration
ondomContentEventFired(handler: (event: PageEvents.domContentEventFiredEvent) => void): void
onloadEventFired(handler: (event: PageEvents.loadEventFiredEvent) => void): void
// ... more events
}📋 Comparison with Python CDP-Use
| Feature | Python CDP-Use | TypeScript CDP-Use |
|---------|---------------|-------------------|
| Type Safety | Runtime (Pydantic) | Compile-time (TypeScript) |
| IDE Support | Basic | Full IntelliSense |
| API Pattern | cdp.send.Domain.method() | client.send.Domain.method() |
| Event Registration | cdp.register.Domain.event() | client.register.Domain.onevent() |
| Error Checking | Runtime | Compile-time + Runtime |
| Auto-completion | Limited | Complete |
🤝 Contributing
- Fork the repository
- Make changes to generators in
src/generator/ - Run
npm run generateto regenerate CDP types - Test with
npm run buildand examples - Submit a pull request
📄 License
MIT License - see LICENSE file for details.
🙏 Acknowledgments
- Original Python CDP-Use library
- Chrome DevTools Protocol team
- TypeScript team for excellent type system
