0
# Browser Integration
1
2
Browser-specific error handling features including global error capture, DOM event telemetry, function wrapping, and automatic instrumentation for enhanced client-side error tracking.
3
4
## Capabilities
5
6
### Function Wrapping
7
8
Wrap functions with error handling and context preservation.
9
10
```typescript { .api }
11
/**
12
* Wrap a function with error handling and optional context
13
* @param fn - Function to wrap with error handling
14
* @param context - Optional context object for additional data
15
* @param before - Optional function to call before wrapped function
16
* @returns Wrapped function that reports errors to Rollbar
17
*/
18
function wrap(fn: Function, context?: any, before?: Function): Function;
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
// Basic function wrapping
25
const safeFn = rollbar.wrap(function() {
26
throw new Error('This will be caught and reported');
27
});
28
29
// With context
30
const processData = rollbar.wrap(function(data) {
31
// Process data
32
return data.map(item => item.value);
33
}, { operation: 'data-processing' });
34
35
// With before hook
36
const apiCall = rollbar.wrap(
37
function(endpoint) {
38
return fetch(endpoint);
39
},
40
{ module: 'api' },
41
function(args) {
42
console.log('Making API call to:', args[0]);
43
}
44
);
45
```
46
47
### Global Error Handling
48
49
Automatically capture uncaught exceptions and unhandled promise rejections.
50
51
```typescript { .api }
52
// Configuration options for global error handling
53
captureUncaught?: boolean;
54
captureUnhandledRejections?: boolean;
55
```
56
57
**Configuration Example:**
58
59
```javascript
60
const rollbar = new Rollbar({
61
accessToken: 'YOUR_CLIENT_ACCESS_TOKEN',
62
captureUncaught: true, // Capture window.onerror events
63
captureUnhandledRejections: true, // Capture unhandled promise rejections
64
environment: 'production'
65
});
66
```
67
68
### DOM Event Telemetry
69
70
Capture DOM events and user interactions for debugging context.
71
72
```typescript { .api }
73
/**
74
* Capture custom telemetry events
75
* @param metadata - Event metadata
76
* @param level - Event severity level
77
* @returns Telemetry event object
78
*/
79
function captureEvent(metadata: object, level: Level): TelemetryEvent;
80
81
interface TelemetryEvent {
82
level: Level;
83
type: string;
84
timestamp_ms: number;
85
body: object;
86
source: string;
87
uuid?: string;
88
}
89
```
90
91
**Usage Examples:**
92
93
```javascript
94
// Capture custom user interaction
95
document.getElementById('submit-btn').addEventListener('click', function(e) {
96
rollbar.captureEvent({
97
type: 'click',
98
element: 'submit-button',
99
userId: getCurrentUser().id
100
}, 'info');
101
});
102
103
// Capture form submission
104
document.getElementById('contact-form').addEventListener('submit', function(e) {
105
rollbar.captureEvent({
106
type: 'form_submit',
107
form: 'contact',
108
fields: Object.keys(new FormData(e.target)).length
109
}, 'info');
110
});
111
```
112
113
### Anonymous Error Detection
114
115
Detect and handle Chrome's anonymous errors.
116
117
```typescript { .api }
118
inspectAnonymousErrors?: boolean;
119
```
120
121
Chrome sometimes reports errors as "Script error" without details. This option enables inspection of anonymous errors.
122
123
**Configuration Example:**
124
125
```javascript
126
const rollbar = new Rollbar({
127
accessToken: 'YOUR_ACCESS_TOKEN',
128
inspectAnonymousErrors: true // Enable anonymous error inspection
129
});
130
```
131
132
### Global Event Handler Wrapping
133
134
Automatically wrap global event handlers with error reporting.
135
136
```typescript { .api }
137
wrapGlobalEventHandlers?: boolean;
138
```
139
140
**Configuration Example:**
141
142
```javascript
143
const rollbar = new Rollbar({
144
accessToken: 'YOUR_ACCESS_TOKEN',
145
wrapGlobalEventHandlers: true // Wrap setTimeout, setInterval, etc.
146
});
147
```
148
149
## Auto-Instrumentation
150
151
Comprehensive automatic instrumentation for browser events and interactions.
152
153
```typescript { .api }
154
interface AutoInstrumentSettings {
155
network?: boolean;
156
networkResponseHeaders?: boolean | string[];
157
networkResponseBody?: boolean;
158
networkRequestBody?: boolean;
159
log?: boolean;
160
dom?: boolean;
161
navigation?: boolean;
162
connectivity?: boolean;
163
contentSecurityPolicy?: boolean;
164
errorOnContentSecurityPolicy?: boolean;
165
}
166
167
type AutoInstrumentOptions = boolean | AutoInstrumentSettings;
168
```
169
170
### Network Instrumentation
171
172
Automatically capture network requests and responses.
173
174
**Configuration Example:**
175
176
```javascript
177
const rollbar = new Rollbar({
178
accessToken: 'YOUR_ACCESS_TOKEN',
179
autoInstrument: {
180
network: true,
181
networkResponseHeaders: ['content-type', 'x-request-id'],
182
networkResponseBody: true,
183
networkRequestBody: false // Don't capture request bodies
184
}
185
});
186
```
187
188
### DOM Instrumentation
189
190
Capture DOM events and user interactions.
191
192
**Configuration Example:**
193
194
```javascript
195
const rollbar = new Rollbar({
196
accessToken: 'YOUR_ACCESS_TOKEN',
197
autoInstrument: {
198
dom: true, // Capture clicks, form submissions, etc.
199
navigation: true, // Capture page navigation events
200
connectivity: true // Capture online/offline events
201
}
202
});
203
```
204
205
### Console Log Instrumentation
206
207
Automatically capture console.log, console.error, etc.
208
209
**Configuration Example:**
210
211
```javascript
212
const rollbar = new Rollbar({
213
accessToken: 'YOUR_ACCESS_TOKEN',
214
autoInstrument: {
215
log: true // Capture console logs as telemetry
216
}
217
});
218
```
219
220
## Telemetry Scrubbing
221
222
Control what DOM elements and data are captured in telemetry.
223
224
```typescript { .api }
225
type TelemetryScrubber = (description: TelemetryScrubberInput) => boolean;
226
227
type TelemetryScrubberInput = DomDescription | null;
228
229
interface DomDescription {
230
tagName: string;
231
id: string | undefined;
232
classes: string[] | undefined;
233
attributes: DomAttribute[];
234
}
235
236
interface DomAttribute {
237
key: DomAttributeKey;
238
value: string;
239
}
240
241
type DomAttributeKey = 'type' | 'name' | 'title' | 'alt';
242
```
243
244
**Usage Example:**
245
246
```javascript
247
const rollbar = new Rollbar({
248
accessToken: 'YOUR_ACCESS_TOKEN',
249
telemetryScrubber: (description) => {
250
if (!description) return false;
251
252
// Don't capture password fields
253
if (description.attributes.some(attr =>
254
attr.key === 'type' && attr.value === 'password'
255
)) {
256
return true; // Scrub this element
257
}
258
259
// Don't capture elements with sensitive classes
260
if (description.classes &&
261
description.classes.some(cls => cls.includes('sensitive'))) {
262
return true;
263
}
264
265
return false; // Don't scrub
266
}
267
});
268
```
269
270
## Browser-Specific Configuration
271
272
### Stack Trace Limit
273
274
Control the maximum number of stack frames captured.
275
276
```typescript { .api }
277
stackTraceLimit?: number;
278
```
279
280
### Source Map Configuration
281
282
Enable source map processing for better error reporting.
283
284
```typescript { .api }
285
interface BrowserPayload {
286
client?: {
287
javascript?: {
288
source_map_enabled?: boolean;
289
guess_uncaught_frames?: boolean;
290
code_version?: string;
291
};
292
};
293
}
294
```
295
296
**Configuration Example:**
297
298
```javascript
299
const rollbar = new Rollbar({
300
accessToken: 'YOUR_ACCESS_TOKEN',
301
payload: {
302
client: {
303
javascript: {
304
source_map_enabled: true,
305
guess_uncaught_frames: true,
306
code_version: '1.2.3'
307
}
308
}
309
}
310
});
311
```
312
313
## Complete Browser Setup Example
314
315
```html
316
<!DOCTYPE html>
317
<html>
318
<head>
319
<title>Rollbar Browser Example</title>
320
<script src="https://cdn.rollbar.com/rollbar.umd.min.js"></script>
321
</head>
322
<body>
323
<h1>My App</h1>
324
<button id="error-btn">Trigger Error</button>
325
<button id="custom-event">Custom Event</button>
326
327
<script>
328
// Initialize Rollbar
329
const rollbar = new Rollbar({
330
accessToken: 'YOUR_POST_CLIENT_ITEM_ACCESS_TOKEN',
331
environment: 'production',
332
333
// Global error handling
334
captureUncaught: true,
335
captureUnhandledRejections: true,
336
337
// Browser-specific options
338
inspectAnonymousErrors: true,
339
wrapGlobalEventHandlers: true,
340
stackTraceLimit: 50,
341
342
// Auto-instrumentation
343
autoInstrument: {
344
network: true,
345
networkResponseHeaders: ['content-type'],
346
dom: true,
347
navigation: true,
348
connectivity: true,
349
log: true
350
},
351
352
// Telemetry settings
353
maxTelemetryEvents: 100,
354
includeItemsInTelemetry: true,
355
356
// Source maps
357
payload: {
358
client: {
359
javascript: {
360
source_map_enabled: true,
361
code_version: '1.0.0'
362
}
363
},
364
person: {
365
id: getUserId(),
366
username: getUsername(),
367
email: getUserEmail()
368
}
369
},
370
371
// Custom telemetry scrubber
372
telemetryScrubber: (description) => {
373
if (!description) return false;
374
375
// Scrub password fields
376
return description.attributes.some(attr =>
377
attr.key === 'type' && attr.value === 'password'
378
);
379
}
380
});
381
382
// Set up event handlers
383
document.getElementById('error-btn').addEventListener('click',
384
rollbar.wrap(function() {
385
throw new Error('Intentional error for testing');
386
}, { button: 'error-btn' })
387
);
388
389
document.getElementById('custom-event').addEventListener('click', function() {
390
rollbar.captureEvent({
391
type: 'button_click',
392
button: 'custom-event',
393
timestamp: Date.now()
394
}, 'info');
395
396
rollbar.info('Custom event button clicked');
397
});
398
399
// Example of manual error reporting
400
window.addEventListener('load', function() {
401
rollbar.info('Page loaded successfully');
402
});
403
404
// Helper functions (implement according to your auth system)
405
function getUserId() {
406
return localStorage.getItem('userId') || 'anonymous';
407
}
408
409
function getUsername() {
410
return localStorage.getItem('username') || 'guest';
411
}
412
413
function getUserEmail() {
414
return localStorage.getItem('userEmail') || '';
415
}
416
</script>
417
</body>
418
</html>
419
```
420
421
## Single Page Application (SPA) Integration
422
423
```javascript
424
// For React, Vue, Angular, etc.
425
const rollbar = new Rollbar({
426
accessToken: 'YOUR_ACCESS_TOKEN',
427
environment: 'production',
428
captureUncaught: true,
429
captureUnhandledRejections: true,
430
431
// SPA-specific settings
432
autoInstrument: {
433
network: true,
434
navigation: true, // Important for SPA route changes
435
dom: true
436
},
437
438
// Custom transform for SPA context
439
transform: function(data, item) {
440
// Add current route information
441
data.context = {
442
route: window.location.pathname,
443
component: getCurrentComponent(), // Your SPA-specific function
444
userId: getCurrentUserId()
445
};
446
}
447
});
448
449
// Example: Capture route changes
450
function onRouteChange(newRoute) {
451
rollbar.captureEvent({
452
type: 'navigation',
453
from: oldRoute,
454
to: newRoute,
455
timestamp: Date.now()
456
}, 'info');
457
}
458
```