Issue with javascript validation in Selenium webdriver c# - javascript

I am trying to validate if a jstree has loaded in the UI before I run a selenium command to click a node in the tree, my issue is with writing the javascript validation in the c# code, any advice ?
class Hello
{
public static void Main(string[] args)
{
IWebDriver Chrome = new ChromeDriver();
Chrome.Url = "http://localhost:60268/Login.aspx";
Chrome.FindElement(By.XPath(".//*[#id='ContentPlaceHolder1_Login1_UserName']")).SendKeys("chinthaka");
Chrome.FindElement(By.XPath(".//*[#id='ContentPlaceHolder1_Login1_Password']")).SendKeys("Welkom123456");
Chrome.FindElement(By.Id("ContentPlaceHolder1_Login1_LoginButton")).Click();
// Rather than checking for the specific element with an explicit wait I have used an implecit wait to poll the dom until all elements have been loaded
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[1]/td/div[#class='ob_spl_toppanel']/div[#class='ob_spl_toppanelcontent']//div[#title='Add a new relation aa']")).Click();
//add record
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[1]/tbody/tr[3]//input[#name='15986B36-838D-4F44-A7C7-04B2AFCA042F']")).SendKeys("MR");
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[1]/tbody/tr[4]//input[#name='91D3E3C9-70C1-47B0-A125-FAAFBCA3C923']")).SendKeys("LOCAL ");
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[1]/tbody/tr[5]/td[1]//input[#name='963F62CE-0C57-435C-AEA8-CE912CA0BFFC']")).SendKeys("DUDE ");
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[1]/tbody/tr[3]//input[#name='C360F8E7-D427-4067-A1E9-34C8644CCD2C']")).SendKeys("PLAIN");
Chrome.FindElement(By.XPath(" //div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[1]/tbody/tr[4]//input[#name='54EF9BEA-1AD3-4CCD-893C-291CEA82A561']")).SendKeys("SIMPLE");
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[1]/tbody/tr[11]/td[3]//input[#name='3015E3A7-13BC-44FB-9844-A12B83F58D40']")).SendKeys("PLAIN#ymail.com");
Chrome.FindElement(By.XPath("//div[#id='Spliter1_RightP_Content']/table[#class='ob_spl_panel']/tbody/tr[3]/td/div[#class='ob_spl_bottompanel']/div[#class='ob_spl_bottompanelcontent']/div/div[4]/div[#class='ng-scope']/div[#class='ng-scope']//div[#class='row']/table[6]/tbody/tr[#class='H2Row']//table[#class='H2Table']//tr[#class='H2Row']/td[2]//input[#name='B3BF78C4-0833-466B-B8F3-85AFA812A4A2']")).SendKeys("jj#ymail.com");
//Drop down
Chrome.FindElement(By.CssSelector(".row > .H2Table:nth-child(2) .H2Row:nth-of-type(1) .H2ComboBox span")).Click();
//[ng-controller] .row > .H2Table:nth-child(2) .H2Row:nth-of-type(1) .chosen-single
Chrome.FindElement(By.CssSelector("[ng-controller] .H2Row:nth-of-type(9) .H2ComboBox span")).Click();
Chrome.FindElement(By.CssSelector("[ng-controller] .H2Row:nth-of-type(13) .H2ComboBox span")).Click();
// calendar
Chrome.FindElement(By.CssSelector("[ng-controller] .H2Table:nth-child(3) [src]")).Click();
Chrome.FindElement(By.CssSelector("[ng-controller] .H2Table:nth-child(4) [src]")).Click();
//save record
Chrome.FindElement(By.XPath("//div[#id='H2ReactMainToolStripContainer']//div[#title='Save']/img[#src='App_Themes/H2React/Icons/Actions-document-save-icon.png']")).Click();
//pop up
new WebDriverWait(Chrome, TimeSpan.FromSeconds(5)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//body[#class='ng-scope']/div[#role='dialog']//div[#class='ui-dialog-buttonset']/button[1]/span[#class='ui-button-text']"))).Click();
// new WebDriverWait(Chrome, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath("//*[#id='R3Tree']")));
JsTree();
Chrome.FindElement(By.LinkText("Address1"));
// Close(Chrome);
//*[#id="13cb117e-2c1e-4262-beaf-24af6ed269e3"]/a/text()
}
//The idea is to make the html page run which contains the javascript code which will check if the Jstree is loaded
public static Action JsTree()
{
System.Diagnostics.Process.Start("");
return null;
}
I am calling the tstree validation before I click the link text element "Address1" gregregregregregregregre

Related

Problem with recaptcha3 for .NET MVC website

I'm quite new in web development, have only couple of weeks of experience.
Currently working on C# website and can't get ReCaptchaV3 to work.
I have a subscribe form that shows up as a modal when user clicks on a "subscribe" button on the bulletin page.
In the form I have hidden input field: <input type="hidden" name="Google-captcha-token" id="GoogleCaptchaToken">
It generates the token when "Sign Up" button of the form is clicked.
My problem is - how to I get a hold of that value on the backend in C#? and then send it to google for verification? I also need to check if value I got from Google is within needed range and everything is good continue submitting the form.
This is where I stuck. I understand that I need to catch that value and work with it in the controller, but don't know how to do that.
Hope someone can help me out on this one.
This is how the code in the controller looks
public class BulletinController : _SharedController {
public ActionResult Index(int p = 0) {
var perPage = 10;
if (p < 1) {
p = 1;
}
var starting = (p * perPage) - perPage;
if (starting < 0) {
starting = 0;
}
var token = HttpContext.Request.Form["Google-captcha-token"];
var ns = new NewsServices();
var newsArticles = ns.GetNewsArticles(starting, perPage);
var count = ns.GetNewsArticlesCount();
ViewBag.Paging = Pagination.Generate(count, starting, perPage);
return View(newsArticles);
}
public ActionResult Details(int id) {
var article = new NewsServices().GetNewsArticleByID(id);
if (article == null) {
return HttpNotFound();
}
return View(article);
}
}
I watched a lot of videos on how it should be done, but none of them worked.
It seems to be a problem that view of the page is already using a model and that model is autogenerated. So looks like I can't use another model. Current model is also a list model (not sure what that exactly means though).
The other thing is that submission of the form is not going through the back-end and done through the constantcontact JavaScript sign up script.
Hope somebody will be able to help. Thanks.

click() function not working for onclick="try {if (isReadyToContinue()) {setBusyIndicator();} else {return false;}} catch (e) {;};" [duplicate]

I used explicit waits and I have the warning:
org.openqa.selenium.WebDriverException:
Element is not clickable at point (36, 72). Other element would receive
the click: ...
Command duration or timeout: 393 milliseconds
If I use Thread.sleep(2000) I don't receive any warnings.
#Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.findElement(By.id("navigationPageButton")).click();
try {
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
} catch (Exception e) {
System.out.println("Oh");
}
driver.findElement(By.cssSelector(btnMenu)).click();
Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}
WebDriverException: Element is not clickable at point (x, y)
This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.
The fields of this exception are :
BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL
DRIVER_INFO : public static final java.lang.String DRIVER_INFO
SESSION_ID : public static final java.lang.String SESSION_ID
About your individual usecase, the error tells it all :
WebDriverException: Element is not clickable at point (x, y). Other element would receive the click
It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).
Solution
The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:
1. Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions Class:
WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
2. Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor to bring the element within the Viewport:
WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
3. The page is getting refreshed before the element gets clickable.
In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.
4. Element is present in the DOM but not clickable.
In this case induce ExplicitWait with ExpectedConditions set to elementToBeClickable for the element to be clickable:
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));
5. Element is present but having temporary Overlay.
In this case, induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.
WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
6. Element is present but having permanent Overlay.
Use JavascriptExecutor to send the click directly on the element.
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
In case you need to use it with Javascript
We can use arguments[0].click() to simulate click operation.
var element = element(by.linkText('webdriverjs'));
browser.executeScript("arguments[0].click()",element);
I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint DOM API to find the element that Selenium wanted me to click on instead:
element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
"return document.elementFromPoint(arguments[0], arguments[1]);",
loc['x'],
loc['y'])
element_to_click.click()
I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.
class elements_not_to_be_animated(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
elements = EC._find_elements(driver, self.locator)
# :animated is an artificial jQuery selector for things that are
# currently animated by jQuery.
return driver.execute_script(
'return !jQuery(arguments[0]).filter(":animated").length;',
elements)
except StaleElementReferenceException:
return False
You can try
WebElement navigationPageButton = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
Scrolling the page to the near by point mentioned in the exception did the trick for me. Below is code snippet:
$wd_host = 'http://localhost:4444/wd/hub';
$capabilities =
[
\WebDriverCapabilityType::BROWSER_NAME => 'chrome',
\WebDriverCapabilityType::PROXY => [
'proxyType' => 'manual',
'httpProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
'sslProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
'noProxy' => PROXY_EXCEPTION // to run locally
],
];
$webDriver = \RemoteWebDriver::create($wd_host, $capabilities, 250000, 250000);
...........
...........
// Wait for 3 seconds
$webDriver->wait(3);
// Scrolls the page vertically by 70 pixels
$webDriver->executeScript("window.scrollTo(0, 70);");
NOTE: I use Facebook php webdriver
If element is not clickable and overlay issue is ocuring we use arguments[0].click().
WebElement ele = driver.findElement(By.xpath("//div[#class='input-group-btn']/input"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
The best solution is to override the click functionality:
public void _click(WebElement element){
boolean flag = false;
while(true) {
try{
element.click();
flag=true;
}
catch (Exception e){
flag = false;
}
if(flag)
{
try{
element.click();
}
catch (Exception e){
System.out.printf("Element: " +element+ " has beed clicked, Selenium exception triggered: " + e.getMessage());
}
break;
}
}
}
In C#, I had problem with checking RadioButton,
and this worked for me:
driver.ExecuteJavaScript("arguments[0].checked=true", radio);
Can try with below code
WebDriverWait wait = new WebDriverWait(driver, 30);
Pass other element would receive the click:<a class="navbar-brand" href="#"></a>
boolean invisiable = wait.until(ExpectedConditions
.invisibilityOfElementLocated(By.xpath("//div[#class='navbar-brand']")));
Pass clickable button id as shown below
if (invisiable) {
WebElement ele = driver.findElement(By.xpath("//div[#id='button']");
ele.click();
}

how to get webElement ID which was clicked at browser using C#?

first of all, I don't want to use "...driver.FindElement..." or any another way that I must to inform any kind of locator like id/xpath/name.
Is there some way to get the id information of a webElement, just clicking on it using C# or Java?
I would like to do something like Selenium IDE does:
1 - MANUALLY to open browser(IE/Firefox/Chrome..) and access an URL.
2 - MANUALLY to click on some field/element on the page and save its respective id.
<div **id="ThisIsWhatINeed"**>
PS: After to get the id information, I need to handle this information on others methods, so I think that the "step 2" above, should be something like a listener with a function returning a string.
Here we go:
private Int32 GetTableRowCount(string tableID)
{
Int32 count = 0;
if (webBrowser1.Document != null)
{
HtmlElement tableElem = webBrowser1.Document.GetElementById(tableID);
if (tableElem != null)
{
foreach (HtmlElement rowElem in tableElem.GetElementsByTagName("TR"))
{
count++;
}
}
else
{
throw(new ArgumentException("No TABLE with an ID of " + tableID + " exists."));
}
}
return(count);
}
Here you may find some information: enter link description here

CKEDITOR 4.3 surrounding data with tags?

I'm using CKEDITOR in version 4.3 and got sections of a html as input.
Now i need to make sure, that the costum-data always got a root tag (in my case a div with the class='CKEDITOR-autoadd).
so when my input is:
<p>jkdhgjkhngvkh</p>
<p>shgnuvzv</p>
my output has to be
<div class='CKEDITOR-autoadd'>
<p>jkdhgjkhngvkh</p>
<p>shgnuvzv</p>
</div>
Does anyone got an idea how i could solve this?
I had the idea of adding a custom plugin like
if(!root-tag found){
add div
}
Summary 2 Problems:
1. How do I surround my custom-data with tags?
2. How do I check / search a root-tag?
regards Sebastian
Edit: the failure in the Java-Applikation happens when:
public Element addSection(String title, String xmlAsString, String lang) throws IOException, JDOMException {
Content content = null;
try {
SAXBuilder saxBuilder = new SAXBuilder();
StringReader reader = new StringReader(xmlAsString);
→ Document doc = saxBuilder.build(reader); ← ERROR = JDOMParseException
content = doc.getRootElement();
content.detach();
}catch (JDOMParseException jdomParseExc) {
content = new Text(xmlAsString);
}
return this.addSection(title, content, lang);
}

How to Display the Html content page wise using webview in android?

hi i create simple app to display html page in webview i use the webview and display the page load time like this.
After this Disable the scroll and use the next and previous button to back and forward contain.
So my code is below.
First onCreate display add webview and load the html file.
mainWebView = (WebView) findViewById(R.id.mainWebView);
mainWebView.setVerticalScrollBarEnabled(false);
mainWebView.setHorizontalScrollBarEnabled(false);
mainWebView.getSettings().setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyWebClient());
mainWebView.setPictureListener(new MyPictureClass());
mainWebView.loadUrl("file:///android_asset/chapter-001.html");
after use the MyWebclient Class for get the Height and width for mainwebview.
class MyWebClient extends WebViewClient
{
#Override
public void onPageFinished(WebView view, String url)
{
System.err.println("Page Finish Call");
lanscapHeight = protraitHeight = findHeight = mainWebView.getHeight();
System.err.println("Find Height->"+findHeight);
System.err.println("Portait Height->"+protraitHeight);
System.err.println("Landscap Height->"+lanscapHeight);
}
}
after this use the myPictureClass to get the webView contain length.
class MyPictureClass implements PictureListener
{
#Override
public void onNewPicture(WebView view, Picture picture)
{
proTraitContain = mainWebView.getContentHeight();
System.err.println("picture Class Call-->"+proTraitContain);
}
}
after this.create button next and previous to display the next and previous page.so use the SimpleOnGestureListener to Detect touch event.
btnNext = (Button) findViewById(R.id.btnNext);
btnNext.setOnTouchListener(this);
btnPrev = (Button) findViewById(R.id.btnPrev);
btnPrev.setOnTouchListener(this);
Override touch Method.
#Override
public boolean onTouch(View view, MotionEvent event)
{
if (view == btnNext)
{
btnClickFlage = true;
gestureDetector.onTouchEvent(event);
} else
{
btnClickFlage = false;
gestureDetector.onTouchEvent(event);
}
return false;
}
implement the SimpleGestureListener class as Below.
class MyGesture extends SimpleOnGestureListener
{
#Override
public boolean onSingleTapUp(MotionEvent e)
{
super.onSingleTapUp(e);
System.err.println("Display Total Contain For Protrait -->"+proTraitContain);
System.err.println("Before Height-->" + findHeight);
if (btnClickFlage)
{
if (findHeight > (proTraitContain+protraitHeight))
{
if(restProtraitFlag)
{
System.err.println("If part In side Flag-->"+findHeight);
findHeight=findHeight+protraitHeight;
restProtraitFlag=false;
//findHeight=findHeight+protraitHeight;
mainWebView.scrollTo(0, findHeight);
System.err.println("If part In side Flag-->"+findHeight);
}else
{
mainWebView.loadUrl("file:///android_asset/chapter-002.html");
restProtraitFlag=true;
}
}
else
{
if(protraitFlag)
{
if(findHeight==protraitHeight)
{
findHeight = protraitHeight;
}else
{
findHeight = findHeight + protraitHeight;
}
protraitFlag=false;
}else
{
findHeight = findHeight + protraitHeight;
}
mainWebView.scrollTo(0, findHeight);
}
}
else
{
restProtraitFlag=true;
if (findHeight<=0)
{
mainWebView.loadUrl("file:///android_asset/chapter-001.html");
System.err.println("Load Previous page");
}
else
{
findHeight = findHeight - protraitHeight;
mainWebView.scrollTo(0, findHeight);
}
}
System.err.println("After Height-->" + findHeight);
}
return true;
}
}
but i can't Display the last page of current html page path.now what to do.any solution please give.it's urgent.
i get the content width properly and use the scrollTo method to display but i can't do it.after last page rest of some contain can't display.
Please saw me the any way.
Thank in advance..
Hi Friends Finally i got my question answer.i use the ScrollTo method to scroll the contain and Display next contain of current page.but problem is there webView Display all contain according device.so all time contain display is higher then this current value.so i use the Webview.getScale(); method to Display how much scale use by webview.according to this i use this method and get current contain of webview in and use Display page wise.its finally its work for me..
Name For CalenderOuthenticationDe
Hello You have to put your HTML in res and then in that you have to keep it in raw after then you can access it like this...
webviewTips.loadUrl("file:///android_res/raw/tips.html");
You are showing the web page stored in your assets folder or from sd card.
So, My advice is that leave this approach and this way to show the web page to user..
And Edit your HTML files and put Anchor Tags in that...using that the user can traverse through the web page easily. (Example for that)

Categories

Resources