0
# Target Management
1
2
Browser target (tab/window) management and session handling for the Chrome DevTools Protocol v85. This functionality allows you to create, attach to, and manage browser contexts and targets for multi-tab automation scenarios.
3
4
## Capabilities
5
6
### V85Target Class
7
8
The main class for target management implementing the idealized Target interface.
9
10
```java { .api }
11
/**
12
* Target management functionality for Chrome DevTools v85
13
*/
14
public class V85Target implements org.openqa.selenium.devtools.idealized.target.Target {
15
/**
16
* Creates a new V85Target instance
17
*/
18
public V85Target();
19
}
20
```
21
22
### Target Discovery
23
24
Get information about available browser targets (tabs, windows, workers, etc.).
25
26
```java { .api }
27
/**
28
* Gets a list of all available targets
29
* @return Command that returns list of target information
30
*/
31
public Command<List<org.openqa.selenium.devtools.idealized.target.model.TargetInfo>> getTargets();
32
```
33
34
**Usage Example:**
35
36
```java
37
import org.openqa.selenium.devtools.v85.V85Target;
38
import org.openqa.selenium.devtools.idealized.target.model.TargetInfo;
39
40
V85Target target = domains.target();
41
42
// Get all available targets
43
List<TargetInfo> targets = devTools.send(target.getTargets());
44
45
// Iterate through targets
46
for (TargetInfo targetInfo : targets) {
47
System.out.printf("Target: %s (%s) - %s%n",
48
targetInfo.getTitle(),
49
targetInfo.getType(),
50
targetInfo.getUrl()
51
);
52
53
if (targetInfo.getType().equals("page")) {
54
System.out.println(" This is a web page target");
55
}
56
}
57
```
58
59
### Target Attachment
60
61
Attach to and detach from specific browser targets to control them.
62
63
```java { .api }
64
/**
65
* Attaches to a target for control
66
* @param targetId - ID of the target to attach to
67
* @return Command that returns a session ID for the attached target
68
*/
69
public Command<SessionID> attachToTarget(TargetID targetId);
70
71
/**
72
* Detaches from a target
73
* @param sessionId - Session ID to detach (optional)
74
* @param targetId - Target ID to detach from (optional)
75
* @return Command to detach from target
76
*/
77
public Command<Void> detachFromTarget(Optional<SessionID> sessionId, Optional<TargetID> targetId);
78
```
79
80
**Usage Example:**
81
82
```java
83
// Find a specific target and attach to it
84
List<TargetInfo> targets = devTools.send(target.getTargets());
85
TargetInfo pageTarget = targets.stream()
86
.filter(t -> t.getType().equals("page") && t.getUrl().contains("example.com"))
87
.findFirst()
88
.orElseThrow(() -> new RuntimeException("Target not found"));
89
90
// Attach to the target
91
SessionID sessionId = devTools.send(target.attachToTarget(pageTarget.getTargetId()));
92
System.out.println("Attached to target with session: " + sessionId);
93
94
// Later, detach from the target
95
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.of(pageTarget.getTargetId())));
96
```
97
98
### Auto-Attachment
99
100
Configure automatic attachment to new targets as they are created.
101
102
```java { .api }
103
/**
104
* Sets up automatic attachment to new targets
105
* @return Command to enable auto-attach for new targets
106
*/
107
public Command<Void> setAutoAttach();
108
```
109
110
**Usage Example:**
111
112
```java
113
// Enable auto-attachment to new targets
114
devTools.send(target.setAutoAttach());
115
116
// Listen for detachment events
117
devTools.addListener(target.detached(), detachedTargetId -> {
118
System.out.println("Target detached: " + detachedTargetId);
119
});
120
```
121
122
### Target Events
123
124
Monitor target lifecycle events.
125
126
```java { .api }
127
/**
128
* Event fired when a target is detached
129
* @return Event for target detachment
130
*/
131
public Event<TargetID> detached();
132
```
133
134
**Usage Example:**
135
136
```java
137
// Monitor target detachment
138
devTools.addListener(target.detached(), targetId -> {
139
System.out.println("Target detached: " + targetId);
140
141
// Clean up any resources associated with this target
142
cleanupTargetResources(targetId);
143
});
144
```
145
146
### Complete Multi-Target Management
147
148
```java
149
import org.openqa.selenium.chrome.ChromeDriver;
150
import org.openqa.selenium.devtools.DevTools;
151
import org.openqa.selenium.devtools.v85.V85Domains;
152
import org.openqa.selenium.devtools.idealized.target.model.TargetInfo;
153
154
ChromeDriver driver = new ChromeDriver();
155
DevTools devTools = driver.getDevTools();
156
devTools.createSession();
157
158
V85Domains domains = new V85Domains(devTools);
159
V85Target target = domains.target();
160
161
// Enable auto-attachment for new targets
162
devTools.send(target.setAutoAttach());
163
164
// Monitor target detachment
165
devTools.addListener(target.detached(), targetId -> {
166
System.out.println("Target detached: " + targetId);
167
});
168
169
// Open a new tab
170
driver.executeScript("window.open('https://example.com', '_blank');");
171
172
// Wait a moment for the new target to be created
173
Thread.sleep(1000);
174
175
// Get all targets
176
List<TargetInfo> targets = devTools.send(target.getTargets());
177
System.out.println("Available targets:");
178
179
Map<TargetID, SessionID> attachedSessions = new HashMap<>();
180
181
for (TargetInfo targetInfo : targets) {
182
System.out.printf("- %s: %s (%s)%n",
183
targetInfo.getTargetId(),
184
targetInfo.getTitle(),
185
targetInfo.getType()
186
);
187
188
// Attach to page targets
189
if (targetInfo.getType().equals("page")) {
190
try {
191
SessionID sessionId = devTools.send(target.attachToTarget(targetInfo.getTargetId()));
192
attachedSessions.put(targetInfo.getTargetId(), sessionId);
193
System.out.println(" Attached with session: " + sessionId);
194
} catch (Exception e) {
195
System.err.println(" Failed to attach: " + e.getMessage());
196
}
197
}
198
}
199
200
// Later, detach from all sessions
201
for (Map.Entry<TargetID, SessionID> entry : attachedSessions.entrySet()) {
202
devTools.send(target.detachFromTarget(
203
Optional.of(entry.getValue()),
204
Optional.of(entry.getKey())
205
));
206
}
207
```
208
209
## Model Classes
210
211
### TargetInfo
212
213
Information about a browser target.
214
215
```java { .api }
216
/**
217
* Information about a browser target
218
*/
219
public class org.openqa.selenium.devtools.idealized.target.model.TargetInfo {
220
/**
221
* Creates target information
222
* @param targetId - Unique target identifier
223
* @param type - Target type (page, background_page, service_worker, etc.)
224
* @param title - Target title
225
* @param url - Target URL
226
* @param attached - Whether target is currently attached
227
* @param openerId - ID of the target that opened this target (if any)
228
* @param browserContextId - Browser context ID (if any)
229
*/
230
public TargetInfo(
231
TargetID targetId,
232
String type,
233
String title,
234
String url,
235
Boolean attached,
236
Optional<TargetID> openerId,
237
Optional<BrowserContextID> browserContextId
238
);
239
240
/**
241
* Gets the target ID
242
* @return Unique target identifier
243
*/
244
public TargetID getTargetId();
245
246
/**
247
* Gets the target type
248
* @return Target type string
249
*/
250
public String getType();
251
252
/**
253
* Gets the target title
254
* @return Target title (usually page title)
255
*/
256
public String getTitle();
257
258
/**
259
* Gets the target URL
260
* @return Target URL
261
*/
262
public String getUrl();
263
264
/**
265
* Checks if the target is attached
266
* @return true if target is attached
267
*/
268
public Boolean getAttached();
269
270
/**
271
* Gets the opener target ID
272
* @return ID of target that opened this one (for popups/new tabs)
273
*/
274
public Optional<TargetID> getOpenerId();
275
276
/**
277
* Gets the browser context ID
278
* @return Browser context identifier
279
*/
280
public Optional<BrowserContextID> getBrowserContextId();
281
}
282
```
283
284
### TargetID
285
286
Unique identifier for a browser target.
287
288
```java { .api }
289
/**
290
* Unique identifier for a browser target
291
*/
292
public class TargetID {
293
/**
294
* Creates a target ID from string
295
* @param id - Target ID string
296
*/
297
public TargetID(String id);
298
299
/**
300
* Gets the ID as string
301
* @return Target ID string
302
*/
303
public String toString();
304
}
305
```
306
307
### SessionID
308
309
Session identifier for attached targets.
310
311
```java { .api }
312
/**
313
* Session identifier for DevTools connection to a target
314
*/
315
public class SessionID {
316
/**
317
* Creates a session ID from string
318
* @param id - Session ID string
319
*/
320
public SessionID(String id);
321
322
/**
323
* Gets the ID as string
324
* @return Session ID string
325
*/
326
public String toString();
327
}
328
```
329
330
### BrowserContextID
331
332
Browser context identifier for isolated browsing contexts.
333
334
```java { .api }
335
/**
336
* Browser context identifier for isolated browsing sessions
337
*/
338
public class BrowserContextID {
339
/**
340
* Creates a browser context ID from string
341
* @param id - Context ID string
342
*/
343
public BrowserContextID(String id);
344
345
/**
346
* Gets the ID as string
347
* @return Context ID string
348
*/
349
public String toString();
350
}
351
```
352
353
## Advanced Target Patterns
354
355
### Target Type Filtering
356
357
```java
358
// Filter targets by type
359
List<TargetInfo> targets = devTools.send(target.getTargets());
360
361
// Get only page targets
362
List<TargetInfo> pageTargets = targets.stream()
363
.filter(t -> t.getType().equals("page"))
364
.collect(Collectors.toList());
365
366
// Get service worker targets
367
List<TargetInfo> serviceWorkers = targets.stream()
368
.filter(t -> t.getType().equals("service_worker"))
369
.collect(Collectors.toList());
370
371
// Get background page targets (extensions)
372
List<TargetInfo> backgroundPages = targets.stream()
373
.filter(t -> t.getType().equals("background_page"))
374
.collect(Collectors.toList());
375
```
376
377
### Multi-Session Management
378
379
```java
380
public class MultiTargetManager {
381
private final Map<TargetID, SessionID> sessions = new ConcurrentHashMap<>();
382
private final DevTools devTools;
383
private final V85Target target;
384
385
public MultiTargetManager(DevTools devTools, V85Target target) {
386
this.devTools = devTools;
387
this.target = target;
388
389
// Monitor target detachment
390
devTools.addListener(target.detached(), this::handleTargetDetached);
391
}
392
393
public SessionID attachToTarget(TargetID targetId) {
394
try {
395
SessionID sessionId = devTools.send(target.attachToTarget(targetId));
396
sessions.put(targetId, sessionId);
397
return sessionId;
398
} catch (Exception e) {
399
throw new RuntimeException("Failed to attach to target: " + targetId, e);
400
}
401
}
402
403
public void detachFromTarget(TargetID targetId) {
404
SessionID sessionId = sessions.remove(targetId);
405
if (sessionId != null) {
406
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.of(targetId)));
407
}
408
}
409
410
public void detachFromAllTargets() {
411
for (Map.Entry<TargetID, SessionID> entry : sessions.entrySet()) {
412
devTools.send(target.detachFromTarget(
413
Optional.of(entry.getValue()),
414
Optional.of(entry.getKey())
415
));
416
}
417
sessions.clear();
418
}
419
420
private void handleTargetDetached(TargetID targetId) {
421
sessions.remove(targetId);
422
System.out.println("Cleaned up session for detached target: " + targetId);
423
}
424
425
public Set<TargetID> getAttachedTargets() {
426
return new HashSet<>(sessions.keySet());
427
}
428
}
429
```
430
431
### Target Monitoring
432
433
```java
434
// Continuous target monitoring
435
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
436
437
executor.scheduleAtFixedRate(() -> {
438
try {
439
List<TargetInfo> currentTargets = devTools.send(target.getTargets());
440
441
System.out.println("Current targets:");
442
for (TargetInfo targetInfo : currentTargets) {
443
System.out.printf(" %s: %s (%s) - %s%n",
444
targetInfo.getTargetId(),
445
targetInfo.getTitle(),
446
targetInfo.getType(),
447
targetInfo.getAttached() ? "attached" : "detached"
448
);
449
}
450
451
// Auto-attach to new page targets
452
for (TargetInfo targetInfo : currentTargets) {
453
if (targetInfo.getType().equals("page") && !targetInfo.getAttached()) {
454
try {
455
SessionID sessionId = devTools.send(target.attachToTarget(targetInfo.getTargetId()));
456
System.out.println("Auto-attached to new page target: " + sessionId);
457
} catch (Exception e) {
458
System.err.println("Failed to auto-attach: " + e.getMessage());
459
}
460
}
461
}
462
463
} catch (Exception e) {
464
System.err.println("Error monitoring targets: " + e.getMessage());
465
}
466
}, 0, 5, TimeUnit.SECONDS);
467
468
// Remember to shutdown the executor when done
469
// executor.shutdown();
470
```