0
# Target Management
1
2
The target domain provides browser target and session management capabilities for handling multiple tabs, windows, browser contexts, and complex automation scenarios requiring fine-grained control over browser instances.
3
4
## Capabilities
5
6
### V101Target
7
8
Target management implementation that provides commands for attaching to, detaching from, and monitoring browser targets.
9
10
```java { .api }
11
/**
12
* Target management for browser contexts and sessions in CDP version 101
13
* Implements the Target interface for managing browser targets and sessions
14
*/
15
public class V101Target implements Target {
16
17
/**
18
* Creates a new target handler instance
19
*/
20
public V101Target();
21
22
/**
23
* Detach from a specific target
24
* @param sessionId Optional session ID to detach from
25
* @param targetId Optional target ID to detach from
26
* @return Command to execute the detachment operation
27
*/
28
public Command<Void> detachFromTarget(Optional<SessionID> sessionId, Optional<TargetID> targetId);
29
30
/**
31
* Get information about all available targets
32
* @return Command that returns a list of target information objects
33
*/
34
public Command<List<TargetInfo>> getTargets();
35
36
/**
37
* Attach to a specific target for debugging and control
38
* @param targetId ID of the target to attach to
39
* @return Command that returns a session ID for the attached target
40
*/
41
public Command<SessionID> attachToTarget(TargetID targetId);
42
43
/**
44
* Enable automatic attachment to new targets as they are created
45
* @return Command to enable auto-attach functionality
46
*/
47
public Command<Void> setAutoAttach();
48
49
/**
50
* Get an event stream for target detachment notifications
51
* @return Event that fires when targets are detached
52
*/
53
public Event<TargetID> detached();
54
}
55
```
56
57
**Usage Examples:**
58
59
```java
60
import org.openqa.selenium.devtools.v101.V101Target;
61
import org.openqa.selenium.devtools.idealized.target.model.*;
62
63
// Create target handler
64
V101Target target = new V101Target();
65
66
// Enable auto-attach for new targets
67
devTools.send(target.setAutoAttach());
68
69
// Get all available targets
70
List<TargetInfo> targets = devTools.send(target.getTargets());
71
System.out.println("Found " + targets.size() + " targets:");
72
73
for (TargetInfo targetInfo : targets) {
74
System.out.println("Target: " + targetInfo.getType() +
75
" - " + targetInfo.getTitle() +
76
" (" + targetInfo.getUrl() + ")");
77
}
78
79
// Find and attach to a specific page target
80
Optional<TargetInfo> pageTarget = targets.stream()
81
.filter(t -> "page".equals(t.getType()))
82
.filter(t -> t.getUrl().contains("example.com"))
83
.findFirst();
84
85
if (pageTarget.isPresent()) {
86
SessionID sessionId = devTools.send(target.attachToTarget(pageTarget.get().getTargetId()));
87
System.out.println("Attached to target with session ID: " + sessionId);
88
89
// Use the session for target-specific operations
90
91
// Detach when done
92
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.of(pageTarget.get().getTargetId())));
93
}
94
95
// Listen for target detachment events
96
devTools.addListener(target.detached(), targetId -> {
97
System.out.println("Target detached: " + targetId);
98
});
99
```
100
101
### TargetInfo
102
103
Information about a browser target including its type, state, and relationships.
104
105
```java { .api }
106
/**
107
* Represents information about a browser target
108
* Contains target identification, type, state, and relationship data
109
*/
110
public class TargetInfo {
111
112
/**
113
* Get the unique identifier for this target
114
* @return TargetID uniquely identifying this target
115
*/
116
public TargetID getTargetId();
117
118
/**
119
* Get the type of target (page, background_page, service_worker, etc.)
120
* @return String representing the target type
121
*/
122
public String getType();
123
124
/**
125
* Get the title of the target (usually the page title)
126
* @return String containing the target title
127
*/
128
public String getTitle();
129
130
/**
131
* Get the URL associated with this target
132
* @return String containing the target URL
133
*/
134
public String getUrl();
135
136
/**
137
* Check if this target has an attached debugging client
138
* @return Boolean indicating if target is attached
139
*/
140
public Boolean getAttached();
141
142
/**
143
* Get the ID of the target that opened this target
144
* @return Optional TargetID of the opener target
145
*/
146
public Optional<TargetID> getOpenerId();
147
148
/**
149
* Get the browser context ID this target belongs to
150
* @return Optional BrowserContextID for the target's context
151
*/
152
public Optional<BrowserContextID> getBrowserContextId();
153
}
154
```
155
156
**Target Types:**
157
158
- `"page"` - Regular web page or tab
159
- `"background_page"` - Extension background page
160
- `"service_worker"` - Service worker instance
161
- `"shared_worker"` - Shared worker instance
162
- `"browser"` - Browser instance itself
163
- `"other"` - Other target types
164
165
**Usage Example:**
166
167
```java
168
// Analyze target hierarchy and relationships
169
List<TargetInfo> targets = devTools.send(target.getTargets());
170
171
for (TargetInfo targetInfo : targets) {
172
System.out.println("=== Target Info ===");
173
System.out.println("ID: " + targetInfo.getTargetId());
174
System.out.println("Type: " + targetInfo.getType());
175
System.out.println("Title: " + targetInfo.getTitle());
176
System.out.println("URL: " + targetInfo.getUrl());
177
System.out.println("Attached: " + targetInfo.getAttached());
178
179
if (targetInfo.getOpenerId().isPresent()) {
180
System.out.println("Opened by: " + targetInfo.getOpenerId().get());
181
}
182
183
if (targetInfo.getBrowserContextId().isPresent()) {
184
System.out.println("Browser Context: " + targetInfo.getBrowserContextId().get());
185
}
186
187
System.out.println();
188
}
189
```
190
191
### ID Wrapper Types
192
193
Type-safe wrappers for various target-related identifiers.
194
195
```java { .api }
196
/**
197
* Wrapper for target identifiers ensuring type safety
198
*/
199
public class TargetID {
200
/**
201
* Create a target ID from a string identifier
202
* @param id String representation of the target ID
203
*/
204
public TargetID(String id);
205
206
/**
207
* Get the string representation of this target ID
208
* @return String ID that can be used in CDP commands
209
*/
210
public String toString();
211
}
212
213
/**
214
* Wrapper for session identifiers ensuring type safety
215
*/
216
public class SessionID {
217
/**
218
* Create a session ID from a string identifier
219
* @param id String representation of the session ID
220
*/
221
public SessionID(String id);
222
223
/**
224
* Get the string representation of this session ID
225
* @return String ID that can be used in CDP commands
226
*/
227
public String toString();
228
}
229
230
/**
231
* Wrapper for browser context identifiers ensuring type safety
232
*/
233
public class BrowserContextID {
234
/**
235
* Create a browser context ID from a string identifier
236
* @param id String representation of the context ID
237
*/
238
public BrowserContextID(String id);
239
240
/**
241
* Get the string representation of this browser context ID
242
* @return String ID that can be used in CDP commands
243
*/
244
public String toString();
245
}
246
```
247
248
### CDP Protocol Commands
249
250
The underlying CDP Target domain commands used by V101Target:
251
252
```java { .api }
253
// From org.openqa.selenium.devtools.v101.target.Target
254
public static Command<GetTargetsResponse> getTargets();
255
public static Command<AttachToTargetResponse> attachToTarget(TargetID targetId, Optional<Boolean> flatten);
256
public static Command<Void> detachFromTarget(Optional<SessionID> sessionId, Optional<TargetID> targetId);
257
public static Command<Void> setAutoAttach(Boolean autoAttach, Boolean waitForDebuggerOnStart, Optional<Boolean> flatten);
258
public static Event<DetachedFromTargetEvent> detachedFromTarget();
259
```
260
261
**Response Types:**
262
263
```java { .api }
264
/**
265
* Response from Target.getTargets command
266
*/
267
public class GetTargetsResponse {
268
public List<TargetInfo> getTargetInfos();
269
}
270
271
/**
272
* Response from Target.attachToTarget command
273
*/
274
public class AttachToTargetResponse {
275
public SessionID getSessionId();
276
}
277
278
/**
279
* Event data when a target is detached
280
*/
281
public class DetachedFromTargetEvent {
282
public SessionID getSessionId();
283
public Optional<TargetID> getTargetId();
284
}
285
```
286
287
## Advanced Usage Patterns
288
289
### Multi-Tab Management
290
291
```java
292
// Manage multiple browser tabs/windows
293
List<TargetInfo> allTargets = devTools.send(target.getTargets());
294
295
// Filter for page targets only
296
List<TargetInfo> pageTargets = allTargets.stream()
297
.filter(t -> "page".equals(t.getType()))
298
.collect(Collectors.toList());
299
300
System.out.println("Found " + pageTargets.size() + " page targets");
301
302
// Attach to each page target for monitoring
303
Map<TargetID, SessionID> activeSessions = new HashMap<>();
304
305
for (TargetInfo pageTarget : pageTargets) {
306
try {
307
SessionID sessionId = devTools.send(target.attachToTarget(pageTarget.getTargetId()));
308
activeSessions.put(pageTarget.getTargetId(), sessionId);
309
System.out.println("Attached to: " + pageTarget.getTitle());
310
} catch (Exception e) {
311
System.err.println("Failed to attach to target " + pageTarget.getTargetId() + ": " + e.getMessage());
312
}
313
}
314
315
// Later, detach from all sessions
316
activeSessions.forEach((targetId, sessionId) -> {
317
try {
318
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.of(targetId)));
319
System.out.println("Detached from target: " + targetId);
320
} catch (Exception e) {
321
System.err.println("Failed to detach from target " + targetId + ": " + e.getMessage());
322
}
323
});
324
```
325
326
### Target Discovery and Filtering
327
328
```java
329
// Advanced target discovery with filtering and categorization
330
public class TargetManager {
331
private final V101Target target;
332
private final DevTools devTools;
333
334
public TargetManager(DevTools devTools) {
335
this.devTools = devTools;
336
this.target = new V101Target();
337
}
338
339
public List<TargetInfo> findPagesByURL(String urlPattern) {
340
List<TargetInfo> targets = devTools.send(target.getTargets());
341
return targets.stream()
342
.filter(t -> "page".equals(t.getType()))
343
.filter(t -> t.getUrl().matches(urlPattern))
344
.collect(Collectors.toList());
345
}
346
347
public List<TargetInfo> findTargetsByType(String targetType) {
348
List<TargetInfo> targets = devTools.send(target.getTargets());
349
return targets.stream()
350
.filter(t -> targetType.equals(t.getType()))
351
.collect(Collectors.toList());
352
}
353
354
public Map<String, List<TargetInfo>> categorizeTargets() {
355
List<TargetInfo> targets = devTools.send(target.getTargets());
356
return targets.stream()
357
.collect(Collectors.groupingBy(TargetInfo::getType));
358
}
359
360
public Optional<TargetInfo> findMainPage() {
361
List<TargetInfo> targets = devTools.send(target.getTargets());
362
return targets.stream()
363
.filter(t -> "page".equals(t.getType()))
364
.filter(t -> !t.getOpenerId().isPresent()) // No opener = main page
365
.findFirst();
366
}
367
}
368
369
// Usage
370
TargetManager targetManager = new TargetManager(devTools);
371
372
// Find all pages matching a pattern
373
List<TargetInfo> apiPages = targetManager.findPagesByURL(".*api\\.example\\.com.*");
374
375
// Categorize all targets
376
Map<String, List<TargetInfo>> targetsByType = targetManager.categorizeTargets();
377
targetsByType.forEach((type, targets) -> {
378
System.out.println(type + ": " + targets.size() + " targets");
379
});
380
381
// Find the main page
382
Optional<TargetInfo> mainPage = targetManager.findMainPage();
383
if (mainPage.isPresent()) {
384
System.out.println("Main page: " + mainPage.get().getTitle());
385
}
386
```
387
388
### Auto-Attach Monitoring
389
390
```java
391
// Set up automatic attachment monitoring for new targets
392
devTools.send(target.setAutoAttach());
393
394
// Listen for new targets being created and attached
395
devTools.addListener(target.detached(), targetId -> {
396
System.out.println("Target detached: " + targetId);
397
398
// Could trigger cleanup or reconnection logic here
399
handleTargetDetachment(targetId);
400
});
401
402
// Periodically check target status
403
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
404
scheduler.scheduleAtFixedRate(() -> {
405
try {
406
List<TargetInfo> currentTargets = devTools.send(target.getTargets());
407
System.out.println("Current target count: " + currentTargets.size());
408
409
// Monitor for unexpected target changes
410
long pageCount = currentTargets.stream()
411
.filter(t -> "page".equals(t.getType()))
412
.count();
413
414
if (pageCount == 0) {
415
System.err.println("Warning: No page targets found!");
416
}
417
418
} catch (Exception e) {
419
System.err.println("Error checking targets: " + e.getMessage());
420
}
421
}, 0, 5, TimeUnit.SECONDS);
422
```
423
424
### Error Handling and Recovery
425
426
```java
427
// Robust target management with error handling
428
public class RobustTargetManager {
429
private final V101Target target;
430
private final DevTools devTools;
431
private final Set<SessionID> activeSessions = ConcurrentHashMap.newKeySet();
432
433
public SessionID attachToTargetSafely(TargetID targetId) {
434
try {
435
SessionID sessionId = devTools.send(target.attachToTarget(targetId));
436
activeSessions.add(sessionId);
437
return sessionId;
438
} catch (Exception e) {
439
System.err.println("Failed to attach to target " + targetId + ": " + e.getMessage());
440
return null;
441
}
442
}
443
444
public void detachFromTargetSafely(SessionID sessionId, TargetID targetId) {
445
try {
446
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.of(targetId)));
447
activeSessions.remove(sessionId);
448
} catch (Exception e) {
449
System.err.println("Failed to detach from target " + targetId + ": " + e.getMessage());
450
}
451
}
452
453
public void cleanupAllSessions() {
454
for (SessionID sessionId : activeSessions) {
455
try {
456
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.empty()));
457
} catch (Exception e) {
458
System.err.println("Error during cleanup of session " + sessionId + ": " + e.getMessage());
459
}
460
}
461
activeSessions.clear();
462
}
463
464
public List<TargetInfo> getTargetsSafely() {
465
try {
466
return devTools.send(target.getTargets());
467
} catch (Exception e) {
468
System.err.println("Error getting targets: " + e.getMessage());
469
return Collections.emptyList();
470
}
471
}
472
}
473
```