Is there a way to return an array from a JavaScript function using Selenium WebDriver? Below is the code I have attempted:
System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
wd=new ChromeDriver();
wd.navigate().to("http://www.makemytrip.com");
wd.manage().window().maximize();
Thread.sleep(5000);
wd.findElement(By.id("from_typeahead1")).click();
WebElement span= wd.findElement(By.xpath(".//*[@id='one_round_default']/div/div[1]/div/div[1]/span/span/div[1]/span"));
JavascriptExecutor jse = (JavascriptExecutor)wd;
jse.executeScript("window.showList = function(){"+
"var source=[];"+
"var inputs = arguments[0].getElementsByTagName('div');"+
"for(var i = 0; i < inputs.length; i++) {"+
"source.push(inputs[i])"+
"}"+
"return source;"+
"};",span);
/*List<?> al = (List<?>) jse.executeScript(
"var source = [];"+
"var inputs = arguments[0].getElementsByTagName('div');"+
"for(var i = 0; i < inputs.length; i++) {"+
"source.push(inputs[i])"+
"}"+
"return source;"
,span);*/
List<?> al = (List<?>) jse.executeScript("showList();");
for(Object web:al){
System.out.println(((WebElement) web).getText());
}
I encountered an exception saying - "org.openqa.selenium.WebDriverException: unknown error: Cannot read property 'getElementsByTagName' of undefined."
Coincidentally, when I try this alternative code, it works perfectly:
System.setProperty("webdriver.chrome.driver", "D:/chromedriver_win32/chromedriver.exe");
wd=new ChromeDriver();
wd.navigate().to("http://www.makemytrip.com");
wd.manage().window().maximize();
Thread.sleep(5000);
wd.findElement(By.id("from_typeahead1")).click();
WebElement span= wd.findElement(By.xpath(".//*[@id='one_round_default']/div/div[1]/div/div[1]/span/span/div[1]/span"));
List<?> al = (List<?>) jse.executeScript(
"var source = [];"+
"var inputs = arguments[0].getElementsByTagName('div');"+
"for(var i = 0; i < inputs.length; i++) {"+
"source.push(inputs[i])"+
"}"+
"return source;"
,span);
for(Object web:al){
System.out.println(((WebElement) web).getText());
}
My goal is to create a function that returns me the array and then call this function whenever needed. How can I achieve this? Also, if possible, how do I utilize an external .js file to implement the same logic and integrate it into my script? Any guidance on this matter would be highly appreciated. Thank you in advance!