or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

console-logging.mddomain-management.mdindex.mdjavascript-execution.mdnetwork-operations.mdruntime-events.mdtarget-management.md

javascript-execution.mddocs/

0

# JavaScript Execution and Binding

1

2

Manages JavaScript execution, binding operations, and script injection for new documents. This domain enables advanced JavaScript interaction capabilities including custom function bindings and automatic script injection.

3

4

## Capabilities

5

6

### V102Javascript Class

7

8

Main class for JavaScript execution and binding operations. Extends the idealized Javascript interface to provide v102-specific implementations for script management and JavaScript bindings.

9

10

```java { .api }

11

/**

12

* Manages JavaScript execution and binding operations

13

*/

14

public class V102Javascript extends Javascript<ScriptIdentifier, BindingCalled> {

15

/**

16

* Creates a new V102Javascript instance with the specified DevTools connection

17

* @param devtools DevTools connection instance (required)

18

*/

19

public V102Javascript(DevTools devtools);

20

21

/**

22

* Enables the Runtime domain for JavaScript operations

23

* @return Command to enable runtime domain

24

*/

25

protected Command<Void> enableRuntime();

26

27

/**

28

* Disables the Runtime domain

29

* @return Command to disable runtime domain

30

*/

31

protected Command<Void> disableRuntime();

32

33

/**

34

* Enables the Page domain for document-level script operations

35

* @return Command to enable page domain

36

*/

37

protected Command<Void> enablePage();

38

39

/**

40

* Disables the Page domain

41

* @return Command to disable page domain

42

*/

43

protected Command<Void> disablePage();

44

45

/**

46

* Adds a JavaScript binding to make Java functions callable from JavaScript

47

* @param scriptName Name of the binding function available in JavaScript

48

* @return Command to add the binding

49

*/

50

protected Command<Void> doAddJsBinding(String scriptName);

51

52

/**

53

* Removes a previously added JavaScript binding

54

* @param scriptName Name of the binding to remove

55

* @return Command to remove the binding

56

*/

57

protected Command<Void> doRemoveJsBinding(String scriptName);

58

59

/**

60

* Adds a script to be evaluated automatically on every new document

61

* @param script JavaScript code to execute on new documents

62

* @return Command returning ScriptIdentifier for the added script

63

*/

64

protected Command<ScriptIdentifier> addScriptToEvaluateOnNewDocument(String script);

65

66

/**

67

* Removes a script that was set to evaluate on new documents

68

* @param id ScriptIdentifier of the script to remove

69

* @return Command to remove the script

70

*/

71

protected Command<Void> removeScriptToEvaluateOnNewDocument(ScriptIdentifier id);

72

73

/**

74

* Returns the binding called event for monitoring JavaScript binding invocations

75

* @return Event for binding call notifications

76

*/

77

protected Event<BindingCalled> bindingCalledEvent();

78

79

/**

80

* Extracts payload from a binding called event

81

* @param event BindingCalled event containing the payload

82

* @return String payload from the binding call

83

*/

84

protected String extractPayload(BindingCalled event);

85

}

86

```

87

88

**Usage Examples:**

89

90

### Basic JavaScript Binding

91

92

```java

93

import org.openqa.selenium.chrome.ChromeDriver;

94

import org.openqa.selenium.devtools.DevTools;

95

import org.openqa.selenium.devtools.v102.V102Domains;

96

97

// Setup

98

ChromeDriver driver = new ChromeDriver();

99

DevTools devTools = driver.getDevTools();

100

devTools.createSession();

101

V102Domains domains = new V102Domains(devTools);

102

103

// Enable JavaScript domain

104

domains.javascript().enable();

105

106

// Add a JavaScript binding

107

devTools.send(domains.javascript().doAddJsBinding("myJavaFunction"));

108

109

// Listen for binding calls

110

devTools.addListener(domains.javascript().bindingCalledEvent(), (event) -> {

111

String payload = domains.javascript().extractPayload(event);

112

System.out.println("JavaScript called Java with payload: " + payload);

113

114

// Process the payload and potentially respond

115

// (Response mechanism depends on your application logic)

116

});

117

118

// Navigate to a page

119

driver.get("https://example.com");

120

121

// Execute JavaScript that calls the binding

122

driver.executeScript("window.myJavaFunction('Hello from JavaScript');");

123

124

// Cleanup

125

devTools.send(domains.javascript().doRemoveJsBinding("myJavaFunction"));

126

domains.javascript().disable();

127

```

128

129

### Script Injection on New Documents

130

131

```java

132

import org.openqa.selenium.devtools.v102.page.model.ScriptIdentifier;

133

134

// Enable both Runtime and Page domains

135

domains.javascript().enable();

136

devTools.send(domains.javascript().enablePage());

137

138

// Add script to run on every new document

139

String initScript = "window.customInit = true; console.log('Custom script loaded');";

140

ScriptIdentifier scriptId = devTools.send(

141

domains.javascript().addScriptToEvaluateOnNewDocument(initScript)

142

);

143

144

// Navigate to pages - the script will run automatically

145

driver.get("https://example.com");

146

driver.get("https://another-site.com");

147

148

// Verify script execution

149

Boolean isInitialized = (Boolean) driver.executeScript("return window.customInit;");

150

System.out.println("Custom script initialized: " + isInitialized);

151

152

// Remove the script when no longer needed

153

devTools.send(domains.javascript().removeScriptToEvaluateOnNewDocument(scriptId));

154

155

// Cleanup

156

devTools.send(domains.javascript().disablePage());

157

```

158

159

### Advanced Binding with Payload Processing

160

161

```java

162

import com.google.gson.Gson;

163

import java.util.Map;

164

165

// Setup binding with JSON payload processing

166

devTools.send(domains.javascript().doAddJsBinding("processData"));

167

168

devTools.addListener(domains.javascript().bindingCalledEvent(), (event) -> {

169

String payload = domains.javascript().extractPayload(event);

170

171

try {

172

// Parse JSON payload

173

Gson gson = new Gson();

174

Map<String, Object> data = gson.fromJson(payload, Map.class);

175

176

// Process the data

177

String action = (String) data.get("action");

178

Object params = data.get("params");

179

180

switch (action) {

181

case "getData":

182

// Return data to JavaScript via executeScript

183

String result = processGetData(params);

184

driver.executeScript("window.handleJavaResponse('" + result + "');");

185

break;

186

case "saveData":

187

processSaveData(params);

188

driver.executeScript("window.handleJavaResponse('saved');");

189

break;

190

}

191

} catch (Exception e) {

192

System.err.println("Error processing binding payload: " + e.getMessage());

193

}

194

});

195

196

// JavaScript side would call:

197

// window.processData(JSON.stringify({action: 'getData', params: {id: 123}}));

198

```

199

200

## CDP Protocol Classes

201

202

The V102Javascript class interacts with generated CDP protocol classes from Runtime and Page domains:

203

204

### Runtime Domain

205

206

```java { .api }

207

// Generated CDP runtime classes (available at runtime)

208

class Runtime {

209

static Command<Void> enable();

210

static Command<Void> disable();

211

static Command<Void> addBinding(String name, Optional<String> executionContextId, Optional<String> executionContextName);

212

static Command<Void> removeBinding(String name);

213

static Event<BindingCalled> bindingCalled();

214

}

215

216

// Binding event data

217

class BindingCalled {

218

String getName();

219

String getPayload();

220

Optional<Integer> getExecutionContextId();

221

}

222

```

223

224

### Page Domain

225

226

```java { .api }

227

// Generated CDP page classes (available at runtime)

228

class Page {

229

static Command<Void> enable();

230

static Command<Void> disable();

231

static Command<ScriptIdentifier> addScriptToEvaluateOnNewDocument(

232

String source,

233

Optional<String> worldName,

234

Optional<Boolean> includeCommandLineAPI

235

);

236

static Command<Void> removeScriptToEvaluateOnNewDocument(ScriptIdentifier identifier);

237

}

238

239

// Script identifier for document scripts

240

class ScriptIdentifier {

241

// Implementation details are version-specific

242

String toString();

243

}

244

```

245

246

### Integration with Selenium

247

248

```java { .api }

249

// Selenium DevTools integration classes

250

abstract class Javascript<ScriptId, BindingEvent> {

251

protected Javascript(DevTools devtools);

252

public void enable();

253

public void disable();

254

}

255

256

class DevTools {

257

<T> T send(Command<T> command);

258

<T> void addListener(Event<T> event, Consumer<T> listener);

259

void createSession();

260

}

261

```

262

263

## JavaScript Binding Patterns

264

265

### Simple Function Binding

266

267

```java

268

// Add binding

269

devTools.send(domains.javascript().doAddJsBinding("log"));

270

271

// Handle calls

272

devTools.addListener(domains.javascript().bindingCalledEvent(), (event) -> {

273

if ("log".equals(event.getName())) {

274

System.out.println("JS Log: " + domains.javascript().extractPayload(event));

275

}

276

});

277

278

// JavaScript usage: window.log("Hello from JS");

279

```

280

281

### Data Exchange Binding

282

283

```java

284

// Bidirectional communication binding

285

devTools.send(domains.javascript().doAddJsBinding("exchange"));

286

287

devTools.addListener(domains.javascript().bindingCalledEvent(), (event) -> {

288

String payload = domains.javascript().extractPayload(event);

289

String response = processPayload(payload);

290

291

// Send response back to JavaScript

292

driver.executeScript("window.handleResponse(arguments[0]);", response);

293

});

294

```

295

296

### Multiple Binding Management

297

298

```java

299

// Add multiple bindings

300

String[] bindings = {"dataService", "logger", "fileHandler"};

301

for (String binding : bindings) {

302

devTools.send(domains.javascript().doAddJsBinding(binding));

303

}

304

305

// Handle all bindings in one listener

306

devTools.addListener(domains.javascript().bindingCalledEvent(), (event) -> {

307

String bindingName = event.getName();

308

String payload = domains.javascript().extractPayload(event);

309

310

switch (bindingName) {

311

case "dataService":

312

handleDataService(payload);

313

break;

314

case "logger":

315

handleLogger(payload);

316

break;

317

case "fileHandler":

318

handleFileHandler(payload);

319

break;

320

}

321

});

322

323

// Cleanup all bindings

324

for (String binding : bindings) {

325

devTools.send(domains.javascript().doRemoveJsBinding(binding));

326

}

327

```