0
# Target Management
1
2
Target management for handling browser tabs, web workers, iframes, and other browsing contexts. Essential for multi-context automation scenarios and advanced browser control.
3
4
## Capabilities
5
6
### Target Discovery
7
8
Discover and list all available targets in the browser session.
9
10
```java { .api }
11
/**
12
* Initialize target management handler
13
*/
14
public V105Target();
15
16
/**
17
* Get list of all available targets
18
* @return Command returning list of target information
19
*/
20
public Command<List<org.openqa.selenium.devtools.idealized.target.model.TargetInfo>> getTargets();
21
```
22
23
**Usage Examples:**
24
25
```java
26
import org.openqa.selenium.devtools.v105.V105Target;
27
import org.openqa.selenium.devtools.idealized.target.model.TargetInfo;
28
import org.openqa.selenium.devtools.idealized.target.model.TargetID;
29
30
// Initialize target management
31
V105Target target = new V105Target();
32
33
// Get all targets
34
List<TargetInfo> targets = devTools.send(target.getTargets());
35
36
// Print target information
37
for (TargetInfo targetInfo : targets) {
38
System.out.println("Target ID: " + targetInfo.getTargetId());
39
System.out.println("Type: " + targetInfo.getType());
40
System.out.println("Title: " + targetInfo.getTitle());
41
System.out.println("URL: " + targetInfo.getUrl());
42
System.out.println("Attached: " + targetInfo.getAttached());
43
System.out.println("---");
44
}
45
```
46
47
### Target Attachment
48
49
Attach to specific targets to control them independently.
50
51
```java { .api }
52
/**
53
* Attach to a specific target for control
54
* @param targetId ID of the target to attach to
55
* @return Command returning session ID for the attached target
56
*/
57
public Command<SessionID> attachToTarget(TargetID targetId);
58
59
/**
60
* Detach from a target
61
* @param sessionId Optional session ID to detach from
62
* @param targetId Optional target ID to detach from
63
* @return Command to detach from target
64
*/
65
public Command<Void> detachFromTarget(Optional<SessionID> sessionId, Optional<TargetID> targetId);
66
```
67
68
**Usage Examples:**
69
70
```java
71
import org.openqa.selenium.devtools.idealized.target.model.SessionID;
72
import java.util.Optional;
73
74
// Find a specific target (e.g., a new tab)
75
List<TargetInfo> targets = devTools.send(target.getTargets());
76
TargetInfo pageTarget = targets.stream()
77
.filter(t -> "page".equals(t.getType()) && !t.getAttached())
78
.findFirst()
79
.orElse(null);
80
81
if (pageTarget != null) {
82
// Attach to the target
83
SessionID sessionId = devTools.send(target.attachToTarget(pageTarget.getTargetId()));
84
System.out.println("Attached with session ID: " + sessionId);
85
86
// Work with the target (send commands using the session)
87
88
// Detach when done
89
devTools.send(target.detachFromTarget(Optional.of(sessionId), Optional.empty()));
90
}
91
```
92
93
### Auto-Attach Configuration
94
95
Configure automatic attachment to new targets as they are created.
96
97
```java { .api }
98
/**
99
* Set up automatic attachment to new targets
100
* @return Command to enable auto-attach with flatten=true
101
*/
102
public Command<Void> setAutoAttach();
103
```
104
105
**Usage Examples:**
106
107
```java
108
// Enable auto-attach for new targets
109
devTools.send(target.setAutoAttach());
110
111
// Now when new tabs, workers, or other targets are created,
112
// they will automatically be attached and available for control
113
114
// Listen for new targets being created
115
target.detached().addListener(targetId -> {
116
System.out.println("Target detached: " + targetId);
117
});
118
119
// Open a new tab - it will be auto-attached
120
((JavascriptExecutor) driver).executeScript("window.open('https://example.com')");
121
122
// Get updated target list
123
List<TargetInfo> updatedTargets = devTools.send(target.getTargets());
124
```
125
126
### Target Event Monitoring
127
128
Monitor target lifecycle events for dynamic target management.
129
130
```java { .api }
131
/**
132
* Get target detached event stream
133
* @return Event stream for target detachment events
134
*/
135
public Event<TargetID> detached();
136
```
137
138
**Usage Examples:**
139
140
```java
141
// Monitor target lifecycle
142
target.detached().addListener(targetId -> {
143
System.out.println("Target detached: " + targetId);
144
// Clean up any resources associated with this target
145
cleanupTarget(targetId);
146
});
147
148
// Create and manage multiple targets
149
public class MultiTargetManager {
150
private final Map<TargetID, SessionID> activeSessions = new ConcurrentHashMap<>();
151
private final V105Target targetManager;
152
153
public MultiTargetManager(DevTools devTools) {
154
this.targetManager = new V105Target();
155
156
// Set up auto-attach
157
devTools.send(targetManager.setAutoAttach());
158
159
// Monitor detachment
160
targetManager.detached().addListener(this::handleTargetDetached);
161
}
162
163
public void attachToAllPages() {
164
List<TargetInfo> targets = devTools.send(targetManager.getTargets());
165
166
for (TargetInfo target : targets) {
167
if ("page".equals(target.getType()) && !target.getAttached()) {
168
SessionID sessionId = devTools.send(targetManager.attachToTarget(target.getTargetId()));
169
activeSessions.put(target.getTargetId(), sessionId);
170
System.out.println("Attached to page: " + target.getTitle());
171
}
172
}
173
}
174
175
private void handleTargetDetached(TargetID targetId) {
176
activeSessions.remove(targetId);
177
System.out.println("Cleaned up session for target: " + targetId);
178
}
179
180
public void detachFromAll() {
181
activeSessions.forEach((targetId, sessionId) -> {
182
devTools.send(targetManager.detachFromTarget(
183
Optional.of(sessionId),
184
Optional.of(targetId)
185
));
186
});
187
activeSessions.clear();
188
}
189
}
190
```
191
192
### Advanced Target Operations
193
194
Work with specific types of targets like service workers, web workers, and iframes.
195
196
**Usage Examples:**
197
198
```java
199
public class AdvancedTargetManagement {
200
201
public void manageServiceWorkers(V105Target targetManager, DevTools devTools) {
202
List<TargetInfo> targets = devTools.send(targetManager.getTargets());
203
204
// Find service workers
205
List<TargetInfo> serviceWorkers = targets.stream()
206
.filter(t -> "service_worker".equals(t.getType()))
207
.collect(Collectors.toList());
208
209
for (TargetInfo sw : serviceWorkers) {
210
System.out.println("Service Worker: " + sw.getUrl());
211
212
// Attach to service worker for debugging
213
SessionID sessionId = devTools.send(targetManager.attachToTarget(sw.getTargetId()));
214
215
// Service worker specific operations can be performed here
216
// using the sessionId to send commands to that specific context
217
218
// Detach when done
219
devTools.send(targetManager.detachFromTarget(
220
Optional.of(sessionId),
221
Optional.of(sw.getTargetId())
222
));
223
}
224
}
225
226
public void manageWebWorkers(V105Target targetManager, DevTools devTools) {
227
List<TargetInfo> targets = devTools.send(targetManager.getTargets());
228
229
// Find web workers
230
List<TargetInfo> webWorkers = targets.stream()
231
.filter(t -> "worker".equals(t.getType()))
232
.collect(Collectors.toList());
233
234
for (TargetInfo worker : webWorkers) {
235
System.out.println("Web Worker: " + worker.getUrl());
236
237
// Attach and control web worker
238
SessionID sessionId = devTools.send(targetManager.attachToTarget(worker.getTargetId()));
239
240
// Execute code in worker context, monitor worker events, etc.
241
}
242
}
243
244
public void findTargetByUrl(V105Target targetManager, DevTools devTools, String urlPattern) {
245
List<TargetInfo> targets = devTools.send(targetManager.getTargets());
246
247
Optional<TargetInfo> matchingTarget = targets.stream()
248
.filter(t -> t.getUrl().contains(urlPattern))
249
.findFirst();
250
251
if (matchingTarget.isPresent()) {
252
TargetInfo target = matchingTarget.get();
253
System.out.println("Found target: " + target.getTitle() + " at " + target.getUrl());
254
255
// Attach and work with the specific target
256
SessionID sessionId = devTools.send(targetManager.attachToTarget(target.getTargetId()));
257
return sessionId;
258
}
259
260
return null;
261
}
262
}
263
```
264
265
## Types
266
267
### Core Target Types
268
269
```java { .api }
270
// Target management implementation
271
public class V105Target implements org.openqa.selenium.devtools.idealized.target.Target {
272
public V105Target();
273
274
Command<List<TargetInfo>> getTargets();
275
Command<SessionID> attachToTarget(TargetID targetId);
276
Command<Void> detachFromTarget(Optional<SessionID> sessionId, Optional<TargetID> targetId);
277
Command<Void> setAutoAttach();
278
Event<TargetID> detached();
279
}
280
```
281
282
### Target Information Types
283
284
```java { .api }
285
// Idealized target information
286
public class org.openqa.selenium.devtools.idealized.target.model.TargetInfo {
287
TargetInfo(TargetID targetId, String type, String title, String url,
288
Boolean attached, Optional<TargetID> openerId, Optional<BrowserContextID> browserContextId);
289
290
TargetID getTargetId();
291
String getType();
292
String getTitle();
293
String getUrl();
294
Boolean getAttached();
295
Optional<TargetID> getOpenerId();
296
Optional<BrowserContextID> getBrowserContextId();
297
}
298
299
// Target identifier
300
public class org.openqa.selenium.devtools.idealized.target.model.TargetID {
301
TargetID(String id);
302
String toString();
303
}
304
305
// Session identifier for attached targets
306
public class org.openqa.selenium.devtools.idealized.target.model.SessionID {
307
SessionID(String id);
308
String toString();
309
}
310
```
311
312
### Browser Context Types
313
314
```java { .api }
315
// Browser context identifier
316
public class org.openqa.selenium.devtools.idealized.browser.model.BrowserContextID {
317
BrowserContextID(String id);
318
String toString();
319
}
320
```
321
322
### CDP Target Types
323
324
```java { .api }
325
// CDP target information
326
public class org.openqa.selenium.devtools.v105.target.model.TargetInfo {
327
TargetID getTargetId();
328
String getType();
329
String getTitle();
330
String getUrl();
331
Boolean getAttached();
332
Optional<TargetID> getOpenerId();
333
Optional<BrowserContextID> getBrowserContextId();
334
}
335
336
// CDP target identifier
337
public class org.openqa.selenium.devtools.v105.target.model.TargetID {
338
TargetID(String id);
339
String toString();
340
}
341
342
// CDP session identifier
343
public class org.openqa.selenium.devtools.v105.target.model.SessionID {
344
SessionID(String id);
345
String toString();
346
}
347
```
348
349
### Target Types
350
351
Common target types you may encounter:
352
353
- **"page"** - Regular web pages and tabs
354
- **"background_page"** - Extension background pages
355
- **"service_worker"** - Service workers
356
- **"worker"** - Web workers and shared workers
357
- **"browser"** - Browser-level target
358
- **"iframe"** - Embedded iframe contexts
359
- **"other"** - Other specialized contexts