到目前为止,我能够提出的最佳解决方案是创建一个处理超时的新线程。由于 WebDriver 不会返回对 FF 和其他某些浏览器的控制,我可以调用线程处理程序,然后使用 Robot 输入凭据并按 Enter(也可以在此处使用 AutoIt)。然后将控件返回给 WebDriver 以继续执行脚本。
//put this where it belongs, say calling a new url, or clicking a link
//assuming necessary imports
int pageLoadTimeout = 10;
String basicAuthUser = "user";
String basicAuthPass = "pass";
String url = "https://yourdomain.com";
WebDriver driver = new FirefoxDriver();
TimeoutThread timeoutThread = new TimeoutThread(pageLoadTimeout);
timeoutThread.start();
driver.get(url);
//if we return from driver.get() call and timeout actually occured, wait for hanlder to complete
if (timeoutThread.timeoutOccurred){
while (!timeoutThread.completed)
Thread.sleep(200);
}
else {
//else cancel the timeout thread
timeoutThread.interrupt();
}
public class TimeoutThread extends Thread {
int timeout;
boolean timeoutOccurred;
boolean completed;
public TimeoutThread(int seconds) {
this.timeout = seconds;
this.completed = false;
this.timeoutOccurred = false;
}
public void run() {
try {
Thread.sleep(timeout * 1000);
this.timeoutOccurred = true;
this.handleTimeout();
this.completed = true;
}
catch (InterruptedException e) {
return;
}
catch (Exception e){
System.out.println("Exception on TimeoutThread.run(): "+e.getMessage());
}
}
public void handleTimeout(){
System.out.println("Typing in user/pass for basic auth prompt");
try {
Robot robot = new Robot();
//type is defined elsewhere - not illustrating for this example
type(basicAuthUser);
Thread.sleep(500);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(500);
type(basicAuthPass);
Thread.sleep(500);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
catch (AWTException e) {
System.out.println("Failed to type keys: "+e.getMessage());
}
}
}