CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-seleniumhq-selenium--selenium-devtools-v85

Chrome DevTools Protocol (CDP) bindings for Selenium WebDriver targeting Chromium version 85

Pending
Overview
Eval results
Files

javascript.mddocs/

JavaScript Execution

JavaScript execution and binding management for the Chrome DevTools Protocol v85. This functionality allows you to execute JavaScript in different browser contexts, create persistent bindings between browser and Java code, and inject scripts that run on page load.

Capabilities

V85Javascript Class

The main class for JavaScript execution extending the base Javascript functionality.

/**
 * JavaScript execution and binding management for Chrome DevTools v85
 */
public class V85Javascript extends Javascript<ScriptIdentifier, BindingCalled> {
    /**
     * Creates a new V85Javascript instance
     * @param devtools - DevTools session for sending commands
     */
    public V85Javascript(DevTools devtools);
}

Runtime Domain Control

Enable and disable the Runtime domain for JavaScript execution.

/**
 * Enables the Runtime domain for JavaScript execution
 * @return Command to enable runtime
 */
protected Command<Void> enableRuntime();

/**
 * Disables the Runtime domain
 * @return Command to disable runtime
 */
protected Command<Void> disableRuntime();

JavaScript Bindings

Create bidirectional communication channels between browser JavaScript and Java code.

/**
 * Adds a JavaScript binding with the specified name
 * @param scriptName - Name of the binding function in JavaScript
 * @return Command to add the binding
 */
protected Command<Void> doAddJsBinding(String scriptName);

/**
 * Removes a JavaScript binding
 * @param scriptName - Name of the binding to remove
 * @return Command to remove the binding
 */
protected Command<Void> doRemoveJsBinding(String scriptName);

/**
 * Event fired when a JavaScript binding is called from the browser
 * @return Event for binding calls
 */
protected Event<BindingCalled> bindingCalledEvent();

/**
 * Extracts the payload from a binding called event
 * @param event - The binding called event
 * @return Payload string from the event
 */
protected String extractPayload(BindingCalled event);

Usage Example:

import org.openqa.selenium.devtools.v85.V85Javascript;

V85Javascript javascript = (V85Javascript) domains.javascript();

// Add a binding using high-level API
javascript.addJsBinding("javaFunction");

// Listen for binding calls using high-level API
javascript.addBindingCalledListener(payload -> {
    System.out.println("JavaScript called javaFunction with: " + payload);
    
    // Process the payload and potentially respond
    processBindingCall(payload);
});

// In the browser, JavaScript can now call:
// window.javaFunction("Hello from JavaScript!");

Page Domain Control

Enable and disable the Page domain for script injection.

/**
 * Enables the Page domain for script injection
 * @return Command to enable page domain
 */
protected Command<Void> enablePage();

/**
 * Disables the Page domain
 * @return Command to disable page domain
 */
protected Command<Void> disablePage();

Script Injection

Inject JavaScript code that runs automatically on new document loads.

/**
 * Adds a script to be evaluated whenever a new document is created
 * @param script - JavaScript code to inject
 * @return Command that returns a ScriptIdentifier for the injected script
 */
protected Command<ScriptIdentifier> addScriptToEvaluateOnNewDocument(String script);

/**
 * Removes a previously injected script
 * @param id - ScriptIdentifier of the script to remove
 * @return Command to remove the script
 */
protected Command<Void> removeScriptToEvaluateOnNewDocument(ScriptIdentifier id);

Usage Example:

import org.openqa.selenium.devtools.idealized.ScriptId;

// Inject a script using high-level API (pin method)
String initScript = """
    console.log('Page loaded with custom script');
    window.customAPI = {
        sendData: function(data) {
            javaFunction(JSON.stringify(data));
        }
    };
    """;

ScriptId scriptId = javascript.pin("customAPI", initScript);

// The script will run automatically on every page load
// ScriptId can be used for reference, but removal requires domain-level control

Complete Workflow Example

Here's a complete example showing JavaScript binding and script injection:

import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.v85.V85Domains;

ChromeDriver driver = new ChromeDriver();
DevTools devTools = driver.getDevTools();
devTools.createSession();

V85Domains domains = new V85Domains(devTools);
V85Javascript javascript = (V85Javascript) domains.javascript();

// Create a binding for Java-JavaScript communication using high-level API
javascript.addJsBinding("sendToJava");

// Listen for JavaScript calls using high-level API
javascript.addBindingCalledListener(data -> {
    System.out.println("Received from JavaScript: " + data);
    
    // Process the data
    handleJavaScriptData(data);
});

// Inject initialization script
String initScript = """
    window.sendMessage = function(message) {
        sendToJava(JSON.stringify({
            type: 'message',
            content: message,
            timestamp: Date.now()
        }));
    };
    
    console.log('Custom API initialized');
    """;

ScriptId scriptId = javascript.pin("sendMessage", initScript);

// Navigate to a page - the script will run automatically
driver.get("https://example.com");

// The page can now call: window.sendMessage("Hello Java!");

CDP Model Classes

ScriptIdentifier

Identifier for injected scripts that can be used to remove them later.

/**
 * Unique identifier for an injected script
 */
public class ScriptIdentifier {
    public String toString();
}

BindingCalled

Event data when a JavaScript binding is called from the browser.

/**
 * Event fired when a JavaScript binding is called
 */
public class BindingCalled {
    /**
     * Gets the name of the called binding
     * @return Binding name
     */
    public String getName();
    
    /**
     * Gets the payload sent from JavaScript
     * @return Payload string
     */
    public String getPayload();
    
    /**
     * Gets the execution context ID where the binding was called
     * @return Execution context ID
     */
    public Optional<Integer> getExecutionContextId();
}

Advanced Patterns

Bidirectional Communication

// Set up bidirectional communication
devTools.send(javascript.doAddJsBinding("javaAPI"));

devTools.addListener(javascript.bindingCalledEvent(), event -> {
    String payload = javascript.extractPayload(event);
    JsonObject request = JsonParser.parseString(payload).getAsJsonObject();
    
    switch (request.get("action").getAsString()) {
        case "getData":
            // Execute JavaScript to send data back
            String responseScript = String.format(
                "window.handleJavaResponse('%s', %s);",
                request.get("id").getAsString(),
                getDataAsJson()
            );
            devTools.send(Runtime.evaluate(responseScript, Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty(), Optional.empty()));
            break;
            
        case "log":
            System.out.println("JS Log: " + request.get("message").getAsString());
            break;
    }
});

Error Handling

try {
    ScriptIdentifier scriptId = devTools.send(javascript.addScriptToEvaluateOnNewDocument(script));
    System.out.println("Script injected successfully: " + scriptId);
} catch (DevToolsException e) {
    System.err.println("Failed to inject script: " + e.getMessage());
}

Install with Tessl CLI

npx tessl i tessl/maven-org-seleniumhq-selenium--selenium-devtools-v85

docs

events.md

index.md

javascript.md

logging.md

network.md

target.md

tile.json