2011/04/15

Moving to Selenium 2 on WebDriver, Part No.3

For following examples we define:
JavaScriptExecutor js = (JavascriptExecutor)driver);


Count elements matching a XPath expression
Selenium 1:
selenium.getXpathCount(location);

Selenium 2:
driver.findElements(By.xpath(location)).size(); 

Set focus to an element


Selenium 1:
selenium.focus( locator );

Selenium 2:

Driver calls "element.focus()" before sending further events as click or keys to the element, so no explicit setting of focus method is necessary. Still, following should work: js.executeScript ("document.getElementById('inputId').focus()");


Handle Confirm or Alert

Selenium 1:
selenium.chooseOkOnNextConfirmation(); // accept
selenium.chooseCancelOnNextConfirmation(); // cancel

Selenium 2:
js.executeScript("window.confirm = function(msg){ return true;};");
js.executeScript("window.confirm = function(msg){ return false;};");

These JavaScript 'hacks' change behaviour of all confirmation dialogs called after their use.

To be a bit more flexible I use set of three methods.
To handle alerts, just just override window.alert instead of window.confirm.

1. Save original handler and sets a custom one.
js.executeScript("window.orig_confirm = window.confirm;");
// always confirm and save a dialog message
js.executeScript("window.confirm = function(msg){ document.last_confirm=msg; return true;};");

2. Retrieve the alert message.
// alternative to selenium.getConfirmation();
String message = (String)js.executeScript("return document.last_confirm");

3. Restore the original handler.
js.executeScript("window.confirm = window.orig_confirm;");


Select a Window
Every window has a name, in our example the name is 'windowName'.

Selenium 1:
selenium.selectWindow("name=windowName");

Selenium 2:
driver.switchTo().window("windowName");