0
# JavaScript Control
1
2
The v133Javascript class provides comprehensive JavaScript execution and management capabilities, enabling developers to inject scripts, create JavaScript bindings, and control script execution in the browser context.
3
4
## Capabilities
5
6
### v133Javascript Class
7
8
Main JavaScript control class that extends the base Javascript functionality with v133-specific implementations.
9
10
```java { .api }
11
/**
12
* v133-specific JavaScript control implementation
13
* Extends Javascript<ScriptIdentifier, BindingCalled> for type-safe script management
14
*/
15
public class v133Javascript extends Javascript<ScriptIdentifier, BindingCalled> {
16
/**
17
* Creates a new v133Javascript instance
18
* @param devtools DevTools instance for communication with browser
19
*/
20
public v133Javascript(DevTools devtools);
21
}
22
```
23
24
### Runtime Domain Control
25
26
Methods for enabling and disabling the runtime domain required for JavaScript operations.
27
28
```java { .api }
29
/**
30
* Enable runtime domain for JavaScript operations
31
* @return Command to enable runtime domain
32
*/
33
protected Command<Void> enableRuntime();
34
35
/**
36
* Disable runtime domain to stop JavaScript operations
37
* @return Command to disable runtime domain
38
*/
39
protected Command<Void> disableRuntime();
40
```
41
42
### JavaScript Binding Management
43
44
Create and manage JavaScript bindings that allow communication between browser JavaScript and Java code.
45
46
```java { .api }
47
/**
48
* Add a JavaScript binding with specified name
49
* @param scriptName Name of the binding to create
50
* @return Command to add the JavaScript binding
51
*/
52
protected Command<Void> doAddJsBinding(String scriptName);
53
54
/**
55
* Remove an existing JavaScript binding
56
* @param scriptName Name of the binding to remove
57
* @return Command to remove the JavaScript binding
58
*/
59
protected Command<Void> doRemoveJsBinding(String scriptName);
60
61
/**
62
* Get the binding called event for monitoring binding usage
63
* @return Event for JavaScript binding calls
64
*/
65
protected Event<BindingCalled> bindingCalledEvent();
66
67
/**
68
* Extract payload from binding called event
69
* @param event BindingCalled event
70
* @return String payload from the binding call
71
*/
72
protected String extractPayload(BindingCalled event);
73
```
74
75
**Usage Example:**
76
77
```java
78
import org.openqa.selenium.devtools.v133.v133Javascript;
79
import org.openqa.selenium.devtools.v133.runtime.model.BindingCalled;
80
81
v133Javascript javascript = new v133Javascript(devTools);
82
83
// Enable JavaScript operations
84
devTools.send(javascript.enableRuntime());
85
86
// Add a JavaScript binding
87
devTools.send(javascript.doAddJsBinding("myBinding"));
88
89
// Listen for binding calls
90
devTools.addListener(javascript.bindingCalledEvent(), (BindingCalled event) -> {
91
String payload = javascript.extractPayload(event);
92
System.out.println("Binding called with payload: " + payload);
93
94
// Process the payload and potentially respond
95
// ... handle the binding call
96
});
97
98
// In browser JavaScript, you can now call:
99
// window.myBinding("some data from browser");
100
```
101
102
### Page Domain Control
103
104
Methods for enabling and disabling the page domain required for document script injection.
105
106
```java { .api }
107
/**
108
* Enable page domain for document script operations
109
* @return Command to enable page domain
110
*/
111
protected Command<Void> enablePage();
112
113
/**
114
* Disable page domain to stop document script operations
115
* @return Command to disable page domain
116
*/
117
protected Command<Void> disablePage();
118
```
119
120
### Document Script Management
121
122
Inject scripts that automatically execute when new documents are created.
123
124
```java { .api }
125
/**
126
* Add a script to be evaluated when new documents are created
127
* @param script JavaScript code to inject
128
* @return Command returning ScriptIdentifier for the injected script
129
*/
130
protected Command<ScriptIdentifier> addScriptToEvaluateOnNewDocument(String script);
131
132
/**
133
* Remove a previously injected document script
134
* @param id ScriptIdentifier of the script to remove
135
* @return Command to remove the script
136
*/
137
protected Command<Void> removeScriptToEvaluateOnNewDocument(ScriptIdentifier id);
138
```
139
140
**Usage Example:**
141
142
```java
143
import org.openqa.selenium.devtools.v133.page.model.ScriptIdentifier;
144
145
// Enable page domain
146
devTools.send(javascript.enablePage());
147
148
// Inject a script that runs on every new document
149
String initScript = """
150
window.seleniumTestMarker = true;
151
console.log('Selenium test script initialized');
152
""";
153
154
ScriptIdentifier scriptId = devTools.send(
155
javascript.addScriptToEvaluateOnNewDocument(initScript)
156
);
157
158
// Later, remove the script
159
devTools.send(javascript.removeScriptToEvaluateOnNewDocument(scriptId));
160
```
161
162
## JavaScript Data Types
163
164
### ScriptIdentifier
165
166
Unique identifier for injected scripts that run on document creation.
167
168
```java { .api }
169
// From org.openqa.selenium.devtools.v133.page.model.ScriptIdentifier
170
public class ScriptIdentifier {
171
public String toString(); // String representation of the script ID
172
}
173
```
174
175
### BindingCalled
176
177
Event data for JavaScript binding calls from the browser to Java code.
178
179
```java { .api }
180
// From org.openqa.selenium.devtools.v133.runtime.model.BindingCalled
181
public class BindingCalled {
182
public String getName(); // Name of the binding that was called
183
public String getPayload(); // Data payload sent from JavaScript
184
public Optional<Integer> getExecutionContextId(); // Context where binding was called
185
}
186
```
187
188
## Advanced JavaScript Patterns
189
190
### Bidirectional Communication
191
192
Combine bindings with script injection for full bidirectional communication:
193
194
```java
195
// Create a communication channel
196
devTools.send(javascript.doAddJsBinding("sendToJava"));
197
198
// Inject script that sets up JavaScript side
199
String communicationScript = """
200
window.javaApi = {
201
send: function(data) {
202
window.sendToJava(JSON.stringify(data));
203
}
204
};
205
206
window.addEventListener('javaMessage', function(event) {
207
console.log('Received from Java:', event.detail);
208
});
209
""";
210
211
devTools.send(javascript.addScriptToEvaluateOnNewDocument(communicationScript));
212
213
// Listen for messages from JavaScript
214
devTools.addListener(javascript.bindingCalledEvent(), (BindingCalled event) -> {
215
if ("sendToJava".equals(event.getName())) {
216
String data = event.getPayload();
217
// Process data from JavaScript
218
219
// Send response back to JavaScript
220
String responseScript = String.format(
221
"window.dispatchEvent(new CustomEvent('javaMessage', {detail: %s}));",
222
"\"Response from Java\""
223
);
224
devTools.send(Runtime.evaluate(responseScript, Optional.empty(),
225
Optional.empty(), Optional.empty(), Optional.empty(),
226
Optional.empty(), Optional.empty(), Optional.empty(),
227
Optional.empty(), Optional.empty(), Optional.empty()));
228
}
229
});
230
```
231
232
### Script State Management
233
234
Track and manage multiple injected scripts:
235
236
```java
237
import java.util.HashMap;
238
import java.util.Map;
239
240
Map<String, ScriptIdentifier> injectedScripts = new HashMap<>();
241
242
// Method to add named script
243
public void addNamedScript(String name, String script) {
244
ScriptIdentifier id = devTools.send(
245
javascript.addScriptToEvaluateOnNewDocument(script)
246
);
247
injectedScripts.put(name, id);
248
}
249
250
// Method to remove named script
251
public void removeNamedScript(String name) {
252
ScriptIdentifier id = injectedScripts.remove(name);
253
if (id != null) {
254
devTools.send(javascript.removeScriptToEvaluateOnNewDocument(id));
255
}
256
}
257
258
// Cleanup all scripts
259
public void cleanupAllScripts() {
260
for (ScriptIdentifier id : injectedScripts.values()) {
261
devTools.send(javascript.removeScriptToEvaluateOnNewDocument(id));
262
}
263
injectedScripts.clear();
264
}
265
```
266
267
## Integration with Runtime Domain
268
269
The v133Javascript class seamlessly integrates with the Runtime domain for:
270
271
- **Script Evaluation**: Direct JavaScript code execution
272
- **Object Inspection**: Examining JavaScript objects and values
273
- **Context Management**: Managing execution contexts across frames
274
- **Exception Handling**: Capturing and processing JavaScript errors
275
276
## Error Handling
277
278
JavaScript operations include comprehensive error handling for:
279
280
- **Binding Failures**: When JavaScript bindings cannot be created or called
281
- **Script Injection Errors**: When scripts fail to inject or execute
282
- **Communication Failures**: When bidirectional communication breaks down
283
- **Context Loss**: When execution contexts become invalid