0
# JavaScript Execution
1
2
Execute JavaScript code in the browser context with safe evaluation, error handling, and support for both synchronous and asynchronous execution.
3
4
## Capabilities
5
6
### Basic JavaScript Execution
7
8
Execute JavaScript code and retrieve results from the browser context.
9
10
```javascript { .api }
11
/**
12
* Execute JavaScript code in browser
13
* @param code - JavaScript code as string or function
14
* @param args - Arguments to pass to the script (optional)
15
* @param cb - Callback receiving (err, result)
16
*/
17
execute(code: string | function, args?: any[], cb?: callback): any;
18
19
/**
20
* Execute JavaScript with safe error handling
21
* @param code - JavaScript code as string or function
22
* @param args - Arguments to pass to the script (optional)
23
* @param cb - Callback receiving (err, result)
24
*/
25
safeExecute(code: string | function, args?: any[], cb?: callback): any;
26
```
27
28
**Usage Examples:**
29
30
```javascript
31
// Execute simple JavaScript
32
browser.execute('return document.title;', function(err, title) {
33
console.log('Page title:', title);
34
});
35
36
// Execute with arguments
37
browser.execute(
38
'return arguments[0] + arguments[1];',
39
[5, 10],
40
function(err, result) {
41
console.log('5 + 10 =', result); // 15
42
}
43
);
44
45
// Execute function (will be serialized)
46
browser.execute(function() {
47
return {
48
url: window.location.href,
49
userAgent: navigator.userAgent,
50
cookieCount: document.cookies.length
51
};
52
}, function(err, info) {
53
console.log('Browser info:', info);
54
});
55
56
// Safe execution handles errors gracefully
57
browser.safeExecute('return nonExistentVariable.property;', function(err, result) {
58
if (err) {
59
console.log('Script error handled safely');
60
} else {
61
console.log('Result:', result);
62
}
63
});
64
```
65
66
### JavaScript Evaluation
67
68
Evaluate JavaScript expressions and return values.
69
70
```javascript { .api }
71
/**
72
* Evaluate JavaScript expression and return result
73
* @param code - JavaScript expression to evaluate
74
* @param cb - Callback receiving (err, value)
75
*/
76
eval(code: string, cb?: callback): any;
77
78
/**
79
* Safely evaluate JavaScript expression
80
* @param code - JavaScript expression to evaluate
81
* @param cb - Callback receiving (err, value)
82
*/
83
safeEval(code: string, cb?: callback): any;
84
```
85
86
**Usage Examples:**
87
88
```javascript
89
// Evaluate expressions
90
browser.eval('document.querySelectorAll("a").length', function(err, linkCount) {
91
console.log('Number of links on page:', linkCount);
92
});
93
94
browser.eval('window.innerWidth', function(err, width) {
95
console.log('Browser width:', width);
96
});
97
98
// Safe evaluation
99
browser.safeEval('someUndefinedVariable', function(err, result) {
100
if (err) {
101
console.log('Variable not defined, using default');
102
result = 'default_value';
103
}
104
console.log('Result:', result);
105
});
106
107
// Promise chain evaluation
108
browser
109
.get('https://example.com')
110
.eval('document.readyState')
111
.then(state => {
112
console.log('Document ready state:', state);
113
if (state === 'complete') {
114
return browser.eval('document.querySelectorAll("img").length');
115
}
116
})
117
.then(imageCount => {
118
console.log('Images on page:', imageCount);
119
});
120
```
121
122
### Asynchronous JavaScript Execution
123
124
Execute JavaScript that requires async operations like AJAX calls or timers.
125
126
```javascript { .api }
127
/**
128
* Execute asynchronous JavaScript code
129
* @param code - Async JavaScript code as string or function
130
* @param args - Arguments to pass to the script (optional)
131
* @param cb - Callback receiving (err, result)
132
*/
133
executeAsync(code: string | function, args?: any[], cb?: callback): any;
134
135
/**
136
* Safely execute asynchronous JavaScript
137
* @param code - Async JavaScript code as string or function
138
* @param args - Arguments to pass to the script (optional)
139
* @param cb - Callback receiving (err, result)
140
*/
141
safeExecuteAsync(code: string | function, args?: any[], cb?: callback): any;
142
```
143
144
**Usage Examples:**
145
146
```javascript
147
// Execute async JavaScript with callback
148
browser.executeAsync(function() {
149
var callback = arguments[arguments.length - 1];
150
151
setTimeout(function() {
152
callback('Delayed result after 2 seconds');
153
}, 2000);
154
}, function(err, result) {
155
console.log('Async result:', result);
156
});
157
158
// AJAX call in browser
159
browser.executeAsync(function() {
160
var callback = arguments[arguments.length - 1];
161
162
fetch('/api/data')
163
.then(response => response.json())
164
.then(data => callback(data))
165
.catch(error => callback({error: error.message}));
166
}, function(err, data) {
167
console.log('API response:', data);
168
});
169
170
// Async with arguments
171
browser.executeAsync(
172
function(url) {
173
var callback = arguments[arguments.length - 1];
174
175
var xhr = new XMLHttpRequest();
176
xhr.open('GET', url);
177
xhr.onload = function() {
178
callback({
179
status: xhr.status,
180
response: xhr.responseText
181
});
182
};
183
xhr.send();
184
},
185
['/api/status'],
186
function(err, response) {
187
console.log('XHR response:', response);
188
}
189
);
190
```
191
192
### DOM Manipulation
193
194
Common DOM operations through JavaScript execution.
195
196
**Usage Examples:**
197
198
```javascript
199
// Modify DOM elements
200
browser.execute(function() {
201
document.getElementById('message').innerHTML = 'Hello from WebDriver!';
202
document.getElementById('message').style.color = 'red';
203
});
204
205
// Trigger events
206
browser.execute(function() {
207
var button = document.getElementById('hidden-button');
208
var event = new MouseEvent('click', {
209
bubbles: true,
210
cancelable: true
211
});
212
button.dispatchEvent(event);
213
});
214
215
// Scroll to element
216
browser.execute(function() {
217
var element = document.querySelector('.target-section');
218
element.scrollIntoView({behavior: 'smooth'});
219
});
220
221
// Get computed styles
222
browser.execute(function() {
223
var element = document.getElementById('styled-element');
224
var styles = window.getComputedStyle(element);
225
return {
226
color: styles.color,
227
fontSize: styles.fontSize,
228
display: styles.display
229
};
230
}, function(err, styles) {
231
console.log('Element styles:', styles);
232
});
233
```
234
235
### Browser API Access
236
237
Access browser APIs and properties through JavaScript execution.
238
239
**Usage Examples:**
240
241
```javascript
242
// Get browser information
243
browser.execute(function() {
244
return {
245
userAgent: navigator.userAgent,
246
language: navigator.language,
247
platform: navigator.platform,
248
cookieEnabled: navigator.cookieEnabled,
249
onLine: navigator.onLine
250
};
251
}, function(err, browserInfo) {
252
console.log('Browser info:', browserInfo);
253
});
254
255
// Access localStorage
256
browser.execute(function() {
257
localStorage.setItem('testKey', 'testValue');
258
return localStorage.getItem('testKey');
259
}, function(err, value) {
260
console.log('LocalStorage value:', value);
261
});
262
263
// Get page performance data
264
browser.execute(function() {
265
var perf = performance.timing;
266
return {
267
domContentLoaded: perf.domContentLoadedEventEnd - perf.navigationStart,
268
pageLoad: perf.loadEventEnd - perf.navigationStart,
269
firstPaint: performance.getEntriesByType('paint')[0]?.startTime
270
};
271
}, function(err, timing) {
272
console.log('Page performance:', timing);
273
});
274
275
// Access geolocation (if available)
276
browser.executeAsync(function() {
277
var callback = arguments[arguments.length - 1];
278
279
if (navigator.geolocation) {
280
navigator.geolocation.getCurrentPosition(
281
position => callback({
282
lat: position.coords.latitude,
283
lng: position.coords.longitude
284
}),
285
error => callback({error: error.message})
286
);
287
} else {
288
callback({error: 'Geolocation not supported'});
289
}
290
}, function(err, location) {
291
console.log('Location:', location);
292
});
293
```
294
295
### Advanced JavaScript Patterns
296
297
Complex JavaScript execution patterns for sophisticated automation.
298
299
**Usage Examples:**
300
301
```javascript
302
// Wait for condition with JavaScript polling
303
browser.executeAsync(function() {
304
var callback = arguments[arguments.length - 1];
305
306
function checkCondition() {
307
if (document.querySelector('.dynamic-content') !== null) {
308
callback(true);
309
} else {
310
setTimeout(checkCondition, 100);
311
}
312
}
313
314
checkCondition();
315
}, function(err, ready) {
316
console.log('Dynamic content loaded:', ready);
317
});
318
319
// Inject and execute external script
320
browser.executeAsync(function() {
321
var callback = arguments[arguments.length - 1];
322
323
var script = document.createElement('script');
324
script.src = 'https://cdn.jsdelivr.net/npm/lodash@4/lodash.min.js';
325
script.onload = function() {
326
callback(typeof _ !== 'undefined');
327
};
328
script.onerror = function() {
329
callback(false);
330
};
331
document.head.appendChild(script);
332
}, function(err, loaded) {
333
console.log('Lodash loaded:', loaded);
334
});
335
336
// Complex form validation
337
browser.execute(function() {
338
var form = document.getElementById('contact-form');
339
var inputs = form.querySelectorAll('input[required]');
340
var validationResults = {};
341
342
inputs.forEach(function(input) {
343
validationResults[input.name] = {
344
value: input.value,
345
valid: input.checkValidity(),
346
validationMessage: input.validationMessage
347
};
348
});
349
350
return validationResults;
351
}, function(err, validation) {
352
console.log('Form validation results:', validation);
353
});
354
355
// Screenshot trigger with custom logic
356
browser.execute(function() {
357
// Hide sensitive information before screenshot
358
var sensitiveElements = document.querySelectorAll('[data-sensitive]');
359
sensitiveElements.forEach(function(el) {
360
el.style.visibility = 'hidden';
361
});
362
363
return sensitiveElements.length;
364
}, function(err, hiddenCount) {
365
console.log('Hidden', hiddenCount, 'sensitive elements');
366
367
browser.takeScreenshot(function(err, screenshot) {
368
// Restore sensitive elements
369
browser.execute(function() {
370
var sensitiveElements = document.querySelectorAll('[data-sensitive]');
371
sensitiveElements.forEach(function(el) {
372
el.style.visibility = 'visible';
373
});
374
});
375
});
376
});
377
```
378
379
### Error Handling and Debugging
380
381
Best practices for handling JavaScript execution errors.
382
383
**Usage Examples:**
384
385
```javascript
386
// Comprehensive error handling
387
browser.execute(function() {
388
try {
389
// Potentially problematic code
390
var result = someComplexOperation();
391
return {success: true, data: result};
392
} catch (error) {
393
return {
394
success: false,
395
error: error.message,
396
stack: error.stack
397
};
398
}
399
}, function(err, result) {
400
if (err) {
401
console.error('WebDriver error:', err);
402
} else if (!result.success) {
403
console.error('JavaScript error:', result.error);
404
} else {
405
console.log('Success:', result.data);
406
}
407
});
408
409
// Debug browser state
410
browser.execute(function() {
411
return {
412
url: window.location.href,
413
readyState: document.readyState,
414
activeElement: document.activeElement.tagName,
415
errorCount: window.jsErrors ? window.jsErrors.length : 0,
416
consoleErrors: window.console._errors || []
417
};
418
}, function(err, debugInfo) {
419
console.log('Browser debug info:', debugInfo);
420
});
421
```