0
# JavaScript Operations
1
2
JavaScript evaluation capabilities with support for bindings, script injection, and runtime interaction. Enables advanced JavaScript automation beyond standard WebDriver execute_script functionality.
3
4
## Capabilities
5
6
### JavaScript Handler Lifecycle
7
8
Manage JavaScript capabilities including bindings, script injection, and runtime interaction.
9
10
```java { .api }
11
/**
12
* Initialize JavaScript handler for runtime operations
13
* @param devtools DevTools session instance
14
*/
15
public V105Javascript(DevTools devtools);
16
17
/**
18
* Disable JavaScript handler and clean up all bindings and scripts
19
*/
20
public void disable();
21
22
/**
23
* Pin a script to be evaluated on new document creation
24
* @param exposeScriptAs Name to expose the script binding as
25
* @param script JavaScript code to inject
26
* @return ScriptId for managing the pinned script
27
*/
28
public ScriptId pin(String exposeScriptAs, String script);
29
```
30
31
**Usage Examples:**
32
33
```java
34
import org.openqa.selenium.devtools.v105.V105Javascript;
35
import org.openqa.selenium.devtools.v105.runtime.Runtime;
36
37
// Initialize JavaScript handler
38
V105Javascript javascript = new V105Javascript(devTools);
39
40
// Pin a script that runs on new document creation
41
ScriptId scriptId = javascript.pin("testBinding",
42
"window.testMode = true; console.log('Test script loaded');");
43
44
// For direct JavaScript evaluation, use CDP directly
45
devTools.send(Runtime.enable());
46
devTools.send(Runtime.evaluate("return document.title"));
47
devTools.send(Runtime.evaluate("console.log('Hello from DevTools')"));
48
49
// Clean up
50
javascript.disable();
51
devTools.send(Runtime.disable());
52
```
53
54
### JavaScript Bindings
55
56
Create bidirectional communication between Java and JavaScript through named bindings.
57
58
```java { .api }
59
/**
60
* Add JavaScript binding for communication with Java
61
* @param scriptName Name of the binding function
62
*/
63
public void addJsBinding(String scriptName);
64
65
/**
66
* Remove JavaScript binding
67
* @param scriptName Name of the binding to remove
68
*/
69
public void removeJsBinding(String scriptName);
70
71
/**
72
* Add listener for binding calls from JavaScript
73
* @param listener Consumer that receives payload strings from JavaScript
74
*/
75
public void addBindingCalledListener(Consumer<String> listener);
76
```
77
78
**Usage Examples:**
79
80
```java
81
import org.openqa.selenium.devtools.v105.runtime.model.BindingCalled;
82
83
// Set up binding listener first
84
javascript.bindingCalledEvent().addListener(bindingCalled -> {
85
String payload = javascript.extractPayload(bindingCalled);
86
System.out.println("Received from JavaScript: " + payload);
87
88
// Process the payload and potentially respond
89
if (payload.equals("request-data")) {
90
// Execute JavaScript to respond
91
devTools.send(Runtime.evaluate("window.javaResponse = 'Data from Java'"));
92
}
93
});
94
95
// Add binding
96
devTools.send(javascript.doAddJsBinding("javaBinding"));
97
98
// Inject JavaScript that uses the binding
99
devTools.send(Runtime.evaluate(
100
"window.javaBinding('Hello from JavaScript');" +
101
"window.javaBinding('request-data');"
102
));
103
104
// Remove binding when done
105
devTools.send(javascript.doRemoveJsBinding("javaBinding"));
106
```
107
108
### Script Injection
109
110
Inject JavaScript code that runs automatically on new document creation.
111
112
```java { .api }
113
/**
114
* Add script to evaluate on new document creation
115
* @param script JavaScript code to inject
116
* @return Command returning script identifier for later removal
117
*/
118
protected Command<ScriptIdentifier> addScriptToEvaluateOnNewDocument(String script);
119
120
/**
121
* Remove previously injected script
122
* @param id Script identifier from addScriptToEvaluateOnNewDocument
123
* @return Command to remove injected script
124
*/
125
protected Command<Void> removeScriptToEvaluateOnNewDocument(ScriptIdentifier id);
126
```
127
128
**Usage Examples:**
129
130
```java
131
import org.openqa.selenium.devtools.v105.page.model.ScriptIdentifier;
132
133
// Inject script that runs on every new page
134
String injectedScript =
135
"window.testMode = true;" +
136
"console.log('Test script loaded');" +
137
"document.addEventListener('DOMContentLoaded', () => {" +
138
" document.body.setAttribute('data-test', 'true');" +
139
"});";
140
141
ScriptIdentifier scriptId = devTools.send(
142
javascript.addScriptToEvaluateOnNewDocument(injectedScript)
143
);
144
145
// Navigate to pages - script will run automatically
146
driver.get("https://example.com");
147
driver.get("https://another-site.com");
148
149
// Verify script execution
150
Boolean testMode = (Boolean) devTools.send(Runtime.evaluate("window.testMode"));
151
System.out.println("Test mode active: " + testMode);
152
153
// Remove script when no longer needed
154
devTools.send(javascript.removeScriptToEvaluateOnNewDocument(scriptId));
155
```
156
157
### Advanced JavaScript Operations
158
159
Combine bindings, script injection, and evaluation for complex scenarios.
160
161
**Usage Examples:**
162
163
```java
164
// Complex automation scenario
165
public class JavaScriptAutomation {
166
private V105Javascript javascript;
167
private DevTools devTools;
168
169
public void setupAdvancedJavaScript() {
170
javascript = new V105Javascript(devTools);
171
172
// Enable domains
173
devTools.send(javascript.enableRuntime());
174
devTools.send(javascript.enablePage());
175
176
// Set up bidirectional communication
177
setupBindings();
178
179
// Inject monitoring script
180
injectMonitoringScript();
181
}
182
183
private void setupBindings() {
184
// Listen for messages from JavaScript
185
javascript.bindingCalledEvent().addListener(this::handleJavaScriptMessage);
186
187
// Add multiple bindings for different purposes
188
devTools.send(javascript.doAddJsBinding("reportError"));
189
devTools.send(javascript.doAddJsBinding("reportMetrics"));
190
devTools.send(javascript.doAddJsBinding("requestData"));
191
}
192
193
private void injectMonitoringScript() {
194
String monitoringScript =
195
"// Error reporting" +
196
"window.addEventListener('error', (e) => {" +
197
" window.reportError(JSON.stringify({" +
198
" message: e.message," +
199
" filename: e.filename," +
200
" lineno: e.lineno" +
201
" }));" +
202
"});" +
203
204
"// Performance monitoring" +
205
"window.addEventListener('load', () => {" +
206
" setTimeout(() => {" +
207
" const perfData = {" +
208
" loadTime: performance.timing.loadEventEnd - performance.timing.navigationStart," +
209
" domReady: performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart" +
210
" };" +
211
" window.reportMetrics(JSON.stringify(perfData));" +
212
" }, 1000);" +
213
"});";
214
215
devTools.send(javascript.addScriptToEvaluateOnNewDocument(monitoringScript));
216
}
217
218
private void handleJavaScriptMessage(BindingCalled event) {
219
String payload = javascript.extractPayload(event);
220
221
// Route messages based on binding name
222
switch (event.getName()) {
223
case "reportError":
224
handleError(payload);
225
break;
226
case "reportMetrics":
227
handleMetrics(payload);
228
break;
229
case "requestData":
230
provideData(payload);
231
break;
232
}
233
}
234
}
235
```
236
237
## Types
238
239
### Core JavaScript Types
240
241
```java { .api }
242
// JavaScript handler implementation
243
public class V105Javascript extends Javascript<ScriptIdentifier, BindingCalled> {
244
public V105Javascript(DevTools devtools);
245
}
246
247
// Script identifier for injected scripts
248
public class ScriptIdentifier {
249
ScriptIdentifier(String id);
250
String toString();
251
}
252
```
253
254
### Binding Types
255
256
```java { .api }
257
// JavaScript binding call event
258
public class BindingCalled {
259
String getName();
260
String getPayload();
261
Optional<ExecutionContextId> getExecutionContextId();
262
}
263
264
// Execution context identifier
265
public class ExecutionContextId {
266
ExecutionContextId(Integer id);
267
Integer toJson();
268
}
269
```
270
271
### Runtime Types
272
273
```java { .api }
274
// Runtime evaluation result
275
public class EvaluateResponse {
276
RemoteObject getResult();
277
Optional<ExceptionDetails> getExceptionDetails();
278
}
279
280
// Remote object from JavaScript
281
public class RemoteObject {
282
RemoteObject.Type getType();
283
Optional<Object> getValue();
284
Optional<String> getDescription();
285
Optional<String> getObjectId();
286
}
287
288
// Exception details from evaluation
289
public class ExceptionDetails {
290
String getText();
291
int getLineNumber();
292
int getColumnNumber();
293
Optional<String> getUrl();
294
Optional<StackTrace> getStackTrace();
295
}
296
```
297
298
### Page Domain Types
299
300
```java { .api }
301
// Script addition options
302
public class AddScriptToEvaluateOnNewDocumentRequest {
303
String getSource();
304
Optional<String> getWorldName();
305
Optional<Boolean> getIncludeCommandLineAPI();
306
}
307
308
// Frame navigation types
309
public class FrameId {
310
FrameId(String id);
311
String toString();
312
}
313
314
// Navigation events
315
public class FrameNavigated {
316
Frame getFrame();
317
NavigationType getType();
318
}
319
```