JavaScript output to a String - java

Is it possible to fetch javascript output to a string in java. I am working with Selenium WebDriver and I expect all child nodes to be listed for which I want to make use of javascript. I am making use of JavascriptExecutor functionality. I want something like this;
JavascriptExecutor js = (JavascriptExecutor)LaunchBrowserTest.driver;
List<String> s = (List<String>)(js.executeScript(" var text = 'aa'; "
+ "var list = document.getElementById('jstree'); "
+ "var anchorlist = document.getElementsByTagName('a'); "
+ "for( i = 0; i < anchorlist.length; i++ ) "
+ "{ "
+ "text = text + anchorlist[i].innerHTML; "
+ "};"
+ "console.log(text);"));
System.out.println("String Array: " + s );
Is there any way I could expect the text outputted and captured into String 's' in java ?
After I get the list, I wanted them to be used in Selenium to click on the nodes as below
WebElement element = driver.findElement(By.linkText(s[i])); where i < s.length
The present output shows me String Array: []
Please suggest me changes/links to get the functionality working.
Answer:
JavascriptExecutor js = (JavascriptExecutor)LaunchBrowserTest.driver;
List<String> s = (List<String>)(js.executeScript(" var text = 'aa'; "
+ "var list = document.getElementById('jstree'); "
+ "var anchorlist = document.getElementsByTagName('a'); "
+ "for( i = 0; i < anchorlist.length; i++ ) "
+ "{ "
+ "text = text + anchorlist[i].innerHTML; "
+ "};"
+ "return text;"));
System.out.println("String Array: " + s );

If you look through the documentation of Selenium JavascriptExecutor and look for the executeScript() method, you will see that your Javascript has to return something in
order to catch it up in Java itself.
Here you can see what kind of data type you will get in Java if your JS script returns
anything.
I hope this helps you out, good luck.

Related

How to fix a error to write a text on a document-body html?

Good morning everybody, I am writing for you to help me for a method that contains an error.
I am trying to automatize a test for writing a text on a document.body.innerHTML with the method executeJavascript but it's block in a code line. What can I do to fix this error :
"org.openqa.selenium.JavascriptException: SyntaxError: unexpected
token: identifier".
Thanks for your help.
Here is my part of the code:
public void publishCommentInFeedback(String commentTxt) {
JLearnSelectorUtils
.findElementByCssSelector(".comment-pane .dbcomment-add A").click();
ActionUtils.switchToFrame(
JLearnSelectorUtils.findElementByCssSelector(".new-comment-container IFRAME")
);
ActionUtils
.executeJavascript("document.body.innerHTML = '" + commentTxt + "'");
ActionUtils.switchToDefaultContent();
JLearnSelectorUtils.findElementByCssSelector(".new-comment-container .btn").click();
ActionUtils.waitUntilElementVisible(60, ".fulldisplay-footer .wysiwyg-editor");
}
Missing ; at the end of the script:
ActionUtils.executeJavascript("document.body.innerHTML = '" + commentTxt + "'");
vs
ActionUtils.executeJavascript("document.body.innerHTML = '" + commentTxt + "';");
A different approach to find the body element:
String desiredText = "Kevens";
String scr = "document.getElementsByTagName('body')[0].innerHTML = '" + desiredText + "';";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
javascriptExecutor.executeScript(scr);

Parse html content for a value

I receive a Http response after a call as Html String and I would like to scrape certain value stored inside the ReportViewer1 variable.
<html>
....................
...........
<script type="text/javascript">
var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {
CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',
ExportButtonText: 'Export',
ExportToolTip: 'Export',
ExportSelectFormatText: 'Export to the selected format',
FirstPageToolTip: 'First page',
LabelOf: 'of',
LastPageToolTip: 'Last Page',
ProcessingReportMessage: 'Generating report...',
NoPageToDisplay: 'No page to display.',
NextPageToolTip: 'Next page',
ParametersToolTip: 'Click to close parameters area|Click to open parameters area',
DocumentMapToolTip: 'Hide document map|Show document map',
PreviousPageToolTip: 'Previous page',
TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',
SessionHasExpiredError: 'Session has expired.',
SessionHasExpiredMessage: 'Please, refresh the page.',
PrintToolTip: 'Print',
RefreshToolTip: 'Refresh',
NavigateBackToolTip: 'Navigate back',
NavigateForwardToolTip: 'Navigate forward',
ReportParametersSelectAllText: '<select all>',
ReportParametersSelectAValueText: '<select a value>',
ReportParametersInvalidValueText: 'Invalid value.',
ReportParametersNoValueText: 'Value required.',
ReportParametersNullText: 'NULL',
ReportParametersPreviewButtonText: 'Preview',
ReportParametersFalseValueLabel: 'False',
ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',
ReportParametersTrueValueLabel: 'True',
MissingReportSource: 'The source of the report definition has not been specified.',
ZoomToPageWidth: 'Page Width',
ZoomToWholePage: 'Full Page'
}, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);
</script>
...................
...................
</html>
The value is a90a0d41efa6429eadfefa42fc529de1 and this is in the middle of this content:
'/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100',
Whats the best way I can parse this value using Java?
Parse the HTML with String class
public class HtmlParser {
public static void main(String args[]){
String result = getValuesProp(html);
System.out.println("Result: "+ result);
}
static String PIVOT = "Telerik.ReportViewer.axd";
public static String getValuesProp(String json) {
String subString;
int i = json.indexOf(PIVOT);
i+= PIVOT.length();
//', chars
i+=2;
subString = json.substring(i);
i = subString.indexOf("'");
i++;
subString = subString.substring(i);
i = subString.indexOf("'");
subString = subString.substring(0,i);
return subString;
}
static String html ="<html>\n" +
"\n" +
"<script type=\"text/javascript\">\n" +
" var ReportViewer1 = new ReportViewer('ReportViewer1', 'ReportViewer1_ReportToolbar', 'ReportViewer1_ReportArea_WaitControl', 'ReportViewer1_ReportArea_ReportCell', 'ReportViewer1_ReportArea_PreviewFrame', 'ReportViewer1_ParametersAreaCell', 'ReportViewer1_ReportArea_ErrorControl', 'ReportViewer1_ReportArea_ErrorLabel', 'ReportViewer1_CP', '/app/Telerik.ReportViewer.axd', 'a90a0d41efa6429eadfefa42fc529de1', 'Percent', '100', '', 'ReportViewer1_EditorPlaceholder', 'ReportViewer1_CalendarFrame', 'ReportViewer1_ReportArea_DocumentMapCell', {\n" +
" CurrentPageToolTip: 'STR_TELERIK_MSG_CUR_PAGE_TOOL_TIP',\n" +
" ExportButtonText: 'Export',\n" +
" ExportToolTip: 'Export',\n" +
" ExportSelectFormatText: 'Export to the selected format',\n" +
" FirstPageToolTip: 'First page',\n" +
" LabelOf: 'of',\n" +
" LastPageToolTip: 'Last Page',\n" +
" ProcessingReportMessage: 'Generating report...',\n" +
" NoPageToDisplay: 'No page to display.',\n" +
" NextPageToolTip: 'Next page',\n" +
" ParametersToolTip: 'Click to close parameters area|Click to open parameters area',\n" +
" DocumentMapToolTip: 'Hide document map|Show document map',\n" +
" PreviousPageToolTip: 'Previous page',\n" +
" TogglePageLayoutToolTip: 'Switch to interactive view|Switch to print preview',\n" +
" SessionHasExpiredError: 'Session has expired.',\n" +
" SessionHasExpiredMessage: 'Please, refresh the page.',\n" +
" PrintToolTip: 'Print',\n" +
" RefreshToolTip: 'Refresh',\n" +
" NavigateBackToolTip: 'Navigate back',\n" +
" NavigateForwardToolTip: 'Navigate forward',\n" +
" ReportParametersSelectAllText: '<select all>',\n" +
" ReportParametersSelectAValueText: '<select a value>',\n" +
" ReportParametersInvalidValueText: 'Invalid value.',\n" +
" ReportParametersNoValueText: 'Value required.',\n" +
" ReportParametersNullText: 'NULL',\n" +
" ReportParametersPreviewButtonText: 'Preview',\n" +
" ReportParametersFalseValueLabel: 'False',\n" +
" ReportParametersInputDataError: 'Missing or invalid parameter value. Please input valid data for all parameters.',\n" +
" ReportParametersTrueValueLabel: 'True',\n" +
" MissingReportSource: 'The source of the report definition has not been specified.',\n" +
" ZoomToPageWidth: 'Page Width',\n" +
" ZoomToWholePage: 'Full Page'\n" +
" }, 'ReportViewer1_ReportArea_ReportArea', 'ReportViewer1_ReportArea_SplitterCell', 'ReportViewer1_ReportArea_DocumentMapCell', true, true, 'PDF', 'ReportViewer1_RSID', true);\n" +
" </script>\n" +
"\n" +
"</html>";
}
I would read the text a line at a time like how most files are read. Because the format will always be the same, you look for a line that begins with the characters "var ReportViewer1." Then you know you have found the line you want. You may need to strip some white space, although it will always be formatted with the same whitespace too (up to you really.)
When you have the line, use the String .split() method to split that line into an array. There are nice delimiters there to split on ... "," or " " or ", " ... again, see what works best for you.
Test the split up line parts for '/app/Telerik.ReportViewer.axd' ... the next member of your split array will be the value you are looking for.
Again, the formatting will always be the same, so you can rely on that to find your variable. Of course, study the html text to make sure it does always follow the same format within the line you are investigating, but looking at it, I assume it probably does.
Again, find your line ... split it on a delimiter ... and use some logic to find the element you are after in the split up line parts.

Unable to Select option from dropdown using JavascrtptExecutor

Can anyone provide me a failsafe(ish) method for selecting text from dropdowns on this page I am practicing on?
https://www.club18-30.com/club18-30
Specifically, the 'from' and 'to' airport dropdowns. I am using the following code:
public void selectWhereFrom(String query, String whereFromSelect) throws InterruptedException {
WebElement dropDownContainer = driver.findElement(By.xpath(departureAirportLocator));
dropDownContainer.click();
selectOption(query,whereFromSelect);
}
public void selectOption(String query, String option) {
String script =
"function selectOption(s) {\r\n" +
" var sel = document.querySelector(' " + query + "');\r\n" +
" for (var i = 0; i < sel.options.length; i++)\r\n" +
" {\r\n" +
" if (sel.options[i].text.indexOf(s) > -1)\r\n" +
" {\r\n" +
" sel.options[i].selected = true;\r\n" +
" break;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"return selectOption('" + option + "');";
javaScriptExecutor(script);
}
This seems to successfully populate the box with text but when I hit 'Search' I then receive a message saying I need to select an option, suggesting it has not registered the selection?
I would rather avoid JavaScriptExecutor but haven't been able to make these Selects work with a regular Selenium Select mechanism
I would set up a function for each dropdown, one for setting the departure airport and another for setting the destination airport. I've tested the code below and it works.
The functions
public static void setDepartureAirport(String airport)
{
driver.findElement(By.cssSelector("div.departureAirport div.departurePoint")).click();
String xpath = "//div[contains(#class, 'departurePoint')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
public static void setDestinationAirport(String airport)
{
driver.findElement(By.cssSelector("div.destinationAirport div.airportSelect")).click();
String xpath = "//div[contains(#class, 'destinationAirport')]//ul//li[contains(#class, 'custom-select-option') and contains(text(), '"
+ airport + "')]";
driver.findElement(By.xpath(xpath)).click();
}
and you call them like
driver.get("https://www.club18-30.com/club18-30");
setDepartureAirport("(MAN)");
setDestinationAirport("(IBZ)");
I would suggest that you use the 3-letter airport codes for your search, e.g. "(MAN)" for Manchester. That will be unique to each airport but you can use any unique part of the text.

Using jQuery with WebDriver (JAVA)

Hi all!
I use WebDriver to automate the test packets. Please help to solve one problem: does not work use the jQuery .. always get the error
org.openqa.selenium.WebDriverException: TypeError: $(...) is null
Testing code:
#Test
public void stage003() throws Exception {
Reporter.log("<p class=\"stageDescr\">Check for uniqueness of identifiers</p>");
JQSS("" +
"var D_id=\"\";" +
"$('[id]').each(function(){" +
"var ids = $('[id=\"'+this.id+'\"]');" +
"if(ids.length>1 && ids[0]==this) {" +
"D_id = D_id + \" \" + this.id;" +
"}" +
"});" +
"if (D_id==\"\") {" +
"return D_id = \"All ID's is unique\";" +
"} else {" +
"return D_id;" +
"}" +
"");
Reporter.log("<p class=\"stageOutline\"> </p>");
}
And
public void JQSS(String SC) {
String test = (String)((JavascriptExecutor) driver).executeScript(
SC
);
Reporter.log("<p>Testing report... "+test+ "</p>");
}
PS: jquery on the page is already connected
I found the problem - on the test page was also MooTols. I changed the $ sign on "jQuery" and it worked

iterate over a set and create a string containing HTML

I have the following code that is used in the Image gallery generating program Jalbum to generate all keywords used for the images in the gallery.
Set allKeywords = new HashSet();
for (AlbumObject ao : currentObjects) {
XmpManager mgr = ao.getXmpManager();
if (mgr != null) {
allKeywords.addAll(mgr.getKeywordSet());
}
}
//get the Iterator
Iterator itr = allKeywords.iterator();
while(itr.hasNext())
out.println(itr.next());
My question is when out.print:
out.println(itr.next());
how can I add html to each individual keyword? I basically want to outprint:
keyword
I am a newbie in this realm so please be gentle!
out.println("" + itr.next() + "");
If you want to call iterator.next() two times
out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + itr.next() + "\">"
+ (itr.hasNext() ? itr.next() : "") + "</a>");
For your requirement I hope mgr.getKeywordSet() returns string
String str = itr.next();
System.out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + str + "\">" + str + "</a>");

Categories

Resources