Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#10810 pick the right target using given window handle #10811

Merged
merged 5 commits into from Jun 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion java/src/org/openqa/selenium/chromium/ChromiumDriver.java
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
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
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
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
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
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