I am writing a selenium test using javascript in Jmeter. When I click on a link on the site, it opens in a new tab by default. The automated browser even switches to this new tab. But, it seems selenium is not switching to the new tab. When I print the inner HTML for the body element (obtained by xpath //body
) after clicking on the link, I get back the source for the first tab, not the second.
When I try to wait for any element at all on the next page (waiting for //div[@id="my-div-on-second-page-only"]
, for example), I get a timeout saying the element was never located (long after I can see the page has finished loading).
I did happen upon this question, but it's for python, and I am also struggling to understand the accepted answer.
Update
My code for switching the tabs currently looks like this:
// Switch tabs
var tabs = WDS.browser.getWindowHandles();
var tab = WDS.browser.getWindowHandle();
WDS.log.info("Tabs: " + tabs + " current: " + tab); // Output below
// Assume always there are only two tabs
for (t in tabs)
{
WDS.log.info("Checking tab " + t);
if (t != tab)
{
WDS.log.info("Switching to " + t);
WDS.browser.switchTo().window(t);
break;
}
}
The output for the line marked with // Output below
is:
Tabs: [CDwindow-A83928D86BA4F6F46C5D7F4B63B674A5, CDwindow-177CF406C98C28DF4AF5E7EC3228B896] current: CDwindow-A83928D86BA4F6F46C5D7F4B63B674A5
I am not even entering the for/in loop. I have tried switching using tabs[index]
, tabs.get(0);
, and tabs.iterator.next();
, but none have worked. I've been scouring the internet all day for some information on the data type returned by WDS.browser.getWindowHandles();
, but just can't seem to find it.
Update 2
I ultimately switched to the Java interpreter. None of the proposed solutions, even the ones in javascript, worked. I suspect there is an issue with the javascript interpreter itself. I'm going to leave the question open in case anyone would like to offer a solution that is tested and works in the Jmeter webdriver extension for future knowledge.
Below is my working Java code. It uses Matias Dominguez's example, which makes the assumption that the last entry in tabs
is the new tab. Although I find Mike Cook's solution seems to be the best in terms of a general solution, Matias' was good enough for my problem.
// Switch tabs
ArrayList tabs = new ArrayList(); // Jmeter interpreter uses <String> by default
tabs.addAll(WDS.browser.getWindowHandles());
String tab = WDS.browser.getWindowHandle();
WDS.log.info("Tabs: " + tabs + " current: " + tab + " Size of tabs: " + tabs.size());
WDS.browser.switchTo().window(tabs.get(tabs.size() - 1));
WDS.log.info("Tabs switched successfully");