Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions java/src/org/openqa/selenium/devtools/DevTools.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.io.Closeable;
import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
Expand All @@ -31,6 +32,8 @@
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.idealized.Domains;
import org.openqa.selenium.devtools.idealized.target.model.SessionID;
Expand All @@ -44,6 +47,7 @@ public class DevTools implements Closeable {
private final Domains protocol;
private final Duration timeout = Duration.ofSeconds(30);
private final Connection connection;
private String windowHandle = null;
private SessionID cdpSession = null;

public DevTools(Function<DevTools, Domains> protocol, Connection connection) {
Expand Down Expand Up @@ -73,6 +77,8 @@ public void disconnectSession() {

SessionID id = cdpSession;
cdpSession = null;
windowHandle = null;

try {
connection.sendAndWait(
cdpSession,
Expand Down Expand Up @@ -135,9 +141,12 @@ public void createSessionIfThereIsNotOne() {
createSessionIfThereIsNotOne(null);
}

public void createSessionIfThereIsNotOne(String windowHandle) {
public void createSessionIfThereIsNotOne(@Nullable String windowHandle) {
if (cdpSession == null) {
createSession(windowHandle);
} else if (!Objects.equals(this.windowHandle, windowHandle)) {
disconnectSession();
attachToWindow(windowHandle);
}
}

Expand All @@ -152,12 +161,20 @@ public void createSession() {
*
* @param windowHandle result of {@link WebDriver#getWindowHandle()}, optional.
*/
public void createSession(String windowHandle) {
public void createSession(@Nullable String windowHandle) {
if (connection.isClosed()) {
connection.reopen();
}
attachToWindow(windowHandle);
}

private void attachToWindow(String windowHandle) {
TargetID targetId = findTarget(windowHandle);
attachToTarget(targetId);
this.windowHandle = windowHandle;
}

private void attachToTarget(TargetID targetId) {
// Starts the session
// CDP creates a parent browser session when websocket connection is made
// Create session that is child of parent browser session and not child of already existing
Expand Down Expand Up @@ -193,6 +210,7 @@ public void createSession(String windowHandle) {
}
}

@NonNull
private TargetID findTarget(String windowHandle) {
// Figure out the targets.
List<TargetInfo> infos =
Expand Down
Loading