Skip to content

Commit

Permalink
#10810 pick the right target using given window handle (#10811)
Browse files Browse the repository at this point in the history
* #10810 pick the right target using given window handle

* #10810 leave parameterless methods createSession() and createSessionIfThereIsNotOne() for backward compatibility

* #10810 log the exception properly

* #10810 split code to smaller methods

Co-authored-by: Diego Molina <diemol@users.noreply.github.com>
  • Loading branch information
asolntsev and diemol authored Jun 29, 2022
1 parent de0a144 commit 4ad0533
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 22 deletions.
2 changes: 1 addition & 1 deletion java/src/org/openqa/selenium/chromium/ChromiumDriver.java
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public void register(Predicate<URI> whenThisMatches, Supplier<Credentials> useTh
Require.nonNull("Check to use to see how we should authenticate", whenThisMatches);
Require.nonNull("Credentials to use when authenticating", useTheseCredentials);

getDevTools().createSessionIfThereIsNotOne();
getDevTools().createSessionIfThereIsNotOne(getWindowHandle());
getDevTools().getDomains().network().addAuthHandler(whenThisMatches, useTheseCredentials);
}

Expand Down
55 changes: 39 additions & 16 deletions java/src/org/openqa/selenium/devtools/DevTools.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.openqa.selenium.devtools;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.devtools.idealized.Domains;
import org.openqa.selenium.devtools.idealized.target.model.SessionID;
import org.openqa.selenium.devtools.idealized.target.model.TargetID;
Expand All @@ -32,10 +33,13 @@
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;

import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class DevTools implements Closeable {
private static final Logger log = Logger.getLogger(DevTools.class.getName());

private final Domains protocol;
private final Duration timeout = Duration.ofSeconds(10);
Expand Down Expand Up @@ -85,22 +89,27 @@ public void clearListeners() {
}

public void createSessionIfThereIsNotOne() {
createSessionIfThereIsNotOne(null);
}

public void createSessionIfThereIsNotOne(String windowHandle) {
if (cdpSession == null) {
createSession();
createSession(windowHandle);
}
}

public void createSession() {
// Figure out the targets.
List<TargetInfo> infos = connection.sendAndWait(cdpSession, getDomains().target().getTargets(), timeout);
createSession(null);
}

// Grab the first "page" type, and glom on to that.
// TODO: Find out which one might be the current one
TargetID targetId = infos.stream()
.filter(info -> "page".equals(info.getType()))
.map(TargetInfo::getTargetId)
.findAny()
.orElseThrow(() -> new DevToolsException("Unable to find target id of a page"));
/**
* Create CDP session on given window/tab (aka target).
* If windowHandle is null, then _some_ target will be selected. It might be a problem only if you have multiple windows/tabs opened.
*
* @param windowHandle result of {@link WebDriver#getWindowHandle()}, optional.
*/
public void createSession(String windowHandle) {
TargetID targetId = findTarget(windowHandle);

// Start the session.
cdpSession = connection
Expand All @@ -114,24 +123,38 @@ public void createSession() {
// Clear the existing logs
connection.send(cdpSession, getDomains().log().clear())
.exceptionally(t -> {
t.printStackTrace();
log.log(Level.SEVERE, t.getMessage(), t);
return null;
})
).get(timeout.toMillis(), MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("Thread has been interrupted", e);
} catch (ExecutionException e) {
Throwable cause = e;
if (e.getCause() != null) {
cause = e.getCause();
}
throw new DevToolsException(cause);
throw new DevToolsException(unwrapCause(e));
} catch (TimeoutException e) {
throw new org.openqa.selenium.TimeoutException(e);
}
}

private TargetID findTarget(String windowHandle) {
// Figure out the targets.
List<TargetInfo> infos = connection.sendAndWait(cdpSession, getDomains().target().getTargets(), timeout);

// Grab the first "page" type, and glom on to that.
// Find out which one might be the current one (using given window handle like "CDwindow-24426957AC62D8BC83E58C184C38AF2D")
return infos.stream()
.filter(info -> "page".equals(info.getType()))
.map(TargetInfo::getTargetId)
.filter(id -> windowHandle == null || windowHandle.contains(id.toString()))
.findAny()
.orElseThrow(() -> new DevToolsException("Unable to find target id of a page"));
}

private Throwable unwrapCause(ExecutionException e) {
return e.getCause() != null ? e.getCause() : e;
}

public SessionID getCdpSession() {
return cdpSession;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public NetworkInterceptor(WebDriver driver, Filter filter) {
}

this.tools = ((HasDevTools) driver).getDevTools();
tools.createSessionIfThereIsNotOne();
tools.createSessionIfThereIsNotOne(driver.getWindowHandle());

tools.getDomains().network().interceptTrafficWith(filter);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public void initializeListener(WebDriver webDriver) {
Require.precondition(webDriver instanceof HasDevTools, "Loggable must implement HasDevTools");

DevTools tools = ((HasDevTools) webDriver).getDevTools();
tools.createSessionIfThereIsNotOne();
tools.createSessionIfThereIsNotOne(webDriver.getWindowHandle());

tools.getDomains().events().addConsoleListener(handler);
}
Expand Down Expand Up @@ -91,7 +91,7 @@ public void initializeListener(WebDriver driver) {
Require.precondition(driver instanceof HasDevTools, "Loggable must implement HasDevTools");

DevTools tools = ((HasDevTools) driver).getDevTools();
tools.createSessionIfThereIsNotOne();
tools.createSessionIfThereIsNotOne(driver.getWindowHandle());

tools.getDomains().javascript().pin("__webdriver_attribute", script);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public void setUp() {
assumeThat(isFirefoxVersionOlderThan(87, driver)).isFalse();

devTools = ((HasDevTools) driver).getDevTools();
devTools.createSessionIfThereIsNotOne();
devTools.createSessionIfThereIsNotOne(driver.getWindowHandle());

try {
devTools.clearListeners();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public void ensureBasicFunctionality() {
driver = new Augmenter().augment(driver);

try (DevTools devTools = ((HasDevTools) driver).getDevTools()) {
devTools.createSessionIfThereIsNotOne();
devTools.createSessionIfThereIsNotOne(driver.getWindowHandle());
Network<?, ?> network = devTools.getDomains().network();
network.setUserAgent("Cheese-Browser 4000");

Expand Down

0 comments on commit 4ad0533

Please sign in to comment.