How to change value of element via JavaScript with Selenium webdriver .NET - javascript

I'm trying to test a popup page with chrome webdriver and selenium2 using .NET, but I'm having issues. I need to change the value of an element after it's window pops up. I need to chage the default "selectedIndexes":["1"]" to "selectedIndexes":["0"]"
The element is:
<input id="tsTabs_ClientState" name="tsTabs_ClientState" type="hidden" autocomplete="off"
value="{"selectedIndexes":["1"], "logEntries":[], "scrollState":{}}">
My code is as follows:
(I've tried both below listed ExecuteScript lines)
Dim chromeDriver = New ChromeDriver("C:\clearcase\Projects\CMS\VbSeTest")
Try
'Chrome Test
chromeDriver.Navigate().GoToUrl("http://localhost/CMS/<location>.aspx")
Dim queryC As IWebElement = chromeDriver.FindElement(By.Id("ctl00_cphM_grd_ctl00_ctl02_ctl00_ACI_btnInitInsert"))
queryC.Click()
Dim current As String = chromeDriver.CurrentWindowHandle
Dim windows = chromeDriver.WindowHandles.AsEnumerable
Dim addOrgWindow As IWebDriver
For Each window In windows
If window <> current Then
addOrgWindow = chromeDriver.SwitchTo.Window(window)
End If
Next
'chromeDriver.ExecuteScript("document.getElementById('tsTabs_ClientState').value='{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}'")
'OR
chromeDriver.ExecuteScript("var tab=$get('tsTabs_ClientState'); tab.value ='{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}'")
addOrgWindow.FindElement(By.Id("Organization_txtName")).SendKeys("MagicKingdom")
addOrgWindow.FindElement(By.Id("Organization_cbIndustry_cb_Input")).SendKeys("REP")
addOrgWindow.FindElement(By.Id("lbAdd")).Click()
chromeDriver.Quit()
Catch e As Exception
chromeDriver.Quit()
MsgBox(e.ToString())
End Try
I keep getting an error at the chromeDriver.ExecuteScript(..... line as:
Started ChromeDriver (v2.1) on port 63559
System.InvalidOperationException: unknown error: Runtime.evaluate threw exceptio
n: SyntaxError: Unexpected identifier
(Session info: chrome=28.0.1500.72)
(Driver info: chromedriver=2.1,platform=Windows NT 6.1 SP1 x86_64)
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response erro
rResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecu
te, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScriptInternal(String script
, Boolean async, Object[] args)
at OpenQA.Selenium.Remote.RemoteWebDriver.ExecuteScript(String script, Object
[] args)
at VbSeTest.PopUpTest.Main() in C:\clearcase\Projects\CMS\VbSeTest\VbSeTest\P
opUpTest.vb:line 89
[8412:6008:0717/103910:ERROR:textfield.h(162)] NOT IMPLEMENTED
The javascript works in the Selenium IDE for running script to set the text field of another hidden client so I was hopping to do something similar here. I know it finds the element but it doesn't run the script. The other Stack answers here, here, or here have not proven to be what I need to solve this issue. Any help is greatly appreciated.

I think the error is in escaping your JSON string:
chromeDriver.ExecuteScript("var tab=$get('tsTabs_ClientState'); tab.value ='{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}'")
Instead, try:
chromeDriver.ExecuteScript("var tab=$get('tsTabs_ClientState'); tab.value =\"{'selectedIndexes':['0'],'logEntries':[],'scrollState':{}}\"")

Related

How to generate XML for label to print in Javascript using DYMO Connect for Desktop

I manage to print a label from DYMO Connect for Desktop v1.3.1. Now I am trying to print the same label using Javascript. The example PrintMeThatLabel.js is a great example. It contains three different label designs in XML. However, I would like to use the design I created wtih DYMO Connect for Desktop. When I try to use the Dymo file (which is an XML file with extension ".dymo") that was saved with DYMO Connect, I get the following error message if I load it with dymo.label.framework.openLabelXml():
{"message":"An error has occurred.","exceptionMessage":"'Element' is an invalid XmlNodeType. Line 22, position 4.","exceptionType":"System.Xml.XmlException","stackTrace":" at System.Xml.XmlReader.ReadEndElement()\r\n at DYMO.LabelAPI.DYMOLabel`1.Deserialize(XmlReader reader)\r\n at DYMO.CrossPlatform.Common.Helpers.SerializationHelper.Deserialize[T](XmlReader reader)\r\n at DYMO.LabelAPI.LabelHelper.ReadAndOpenLabel(XmlReader reader)\r\n at DYMO.LabelAPI.LabelHelper.OpenLabel(XmlReader reader)\r\n at DymoSDK.Implementations.DymoLabel.LoadLabelFromXML(String xmlContent)\r\n at DYMOWebApi.Windows.Controllers.DymoDLSSDKController.GetListLabelsFromSetXML(String labelXml, String labelSetXml)\r\n at DYMOWebApi.Windows.Controllers.DymoDLSSDKController.PrintLabel2(FormDataCollection formDataCollection)\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass6_2.<GetExecutor>b__2(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"}:
at Td (DYMO.Label.Framework.3.0.js:61)
at ae (DYMO.Label.Framework.3.0.js:66)
at be.printLabel2 (DYMO.Label.Framework.3.0.js:67)
at Object.printLabel2 (DYMO.Label.Framework.3.0.js:101)
at oe (DYMO.Label.Framework.3.0.js:126)
at qe (DYMO.Label.Framework.3.0.js:129)
at Y.G (DYMO.Label.Framework.3.0.js:74)
at printLabel (207:608)
at startupCode (207:617)
at DYMO.Label.Framework.3.0.js:110
If I use openLabelFile instead of openLabelXml I get this error in the console:
Uncaught Error: "Illegal characters in path."
"Illegal characters in path.":
at Td (DYMO.Label.Framework.3.0.js:61)
at ae (DYMO.Label.Framework.3.0.js:66)
at be.openLabelFile (DYMO.Label.Framework.3.0.js:67)
at Object.openLabelFile (DYMO.Label.Framework.3.0.js:101)
at Object.openLabelFile (DYMO.Label.Framework.3.0.js:122)
at printLabel (207:595)
at startupCode (207:617)
at DYMO.Label.Framework.3.0.js:110
at e (DYMO.Label.Framework.3.0.js:115)
at cd.<anonymous> (DYMO.Label.Framework.3.0.js:62)
The XML in the file from DYMO Connect looks very different from the XML of the label designs in PrintMeThatLabel.js. Can anyone help me?
I had the same problem as you this morning!
The newest javascript framework is not compatible with label templates created with Dymo Connect. You need to create it with the previous software. Version 8.3.1 works.
Watch out though, both softwares installed and your code won't recognize the printer. You'll need to uninstall both softwares and re-install Dymo Connect.
Hope this helps!
Yan

Illegal invocation of javascript

Dim bot As Selenium.ChromeDriver
Public Sub WebTest()
Set bot = New Selenium.ChromeDriver
Dim kys As New SeleniumWrapper.keys, arr(), i As Long
arr = Application.Transpose(Selection)
With bot
.Get "https://www.gandhi.com.mx/", -1, True
For i = LBound(arr) To UBound(arr)
If Not IsEmpty(arr(i)) Then
If i > 1 Then
.ExecuteScript "window.open('https://www.gandhi.com.mx/')"
End If
.FindElementByCss("[name=q]").SendKeys arr(i)
.SendKeys bot.keys.Enter
End If
Next
End With
Application.SendKeys "{NUMLOCK}", True
MsgBox "Completed"
End Sub
This is the whole code and i'm assigning the same to a button in excel. The code works fine while opening two or three chrome tabs and shows the below error.
javascript error
javascript error: illegal invocation
I have tried using Application.SendKeys ("^t") and its working. But I could not navigate to any other window while my macro running. If I navigate Ctrl+t works on that application. And i'm getting WindowNotFound Error.
And also I tried using webdriver to open new chrome tab as shown below and it doesn't work.
bot.SendKeys kys.Control, "t"

Synchronization problems with automated testing Angular website with Selenium and testing issues with Internet Explorer.

I am trying to write an automated test program for one of my website using Selenium WEbDriver. I am having some problems when doing the test on Internet Explorer. The website that I am trying to test is built in AngularJS. I will explain my problems in detail.
Here, is the code that waits until Angular has finished processing.
private static ExpectedCondition angularHasFinishedProcessing() {
return (ExpectedCondition<Boolean>) driver -> {
String hasAngularFinishedScript = "var callback = arguments[arguments.length - 1];\n" +
"var el = document.querySelector('html');\n" +
"if (!window.angular) {\n" +
" callback('false')\n" +
"}\n" +
"if (angular.getTestability) {\n" +
" angular.getTestability(el).whenStable(function(){callback('true')});\n" +
"} else {\n" +
" if (!angular.element(el).injector()) {\n" +
" callback('false')\n" +
" }\n" +
" var browser = angular.element(el).injector().get('$browser');\n" +
" browser.notifyWhenNoOutstandingRequests(function(){callback('true')});\n" +
"}";
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
assert javascriptExecutor != null;
String isProcessingFinished = javascriptExecutor.executeAsyncScript(hasAngularFinishedScript).toString();
return Boolean.valueOf(isProcessingFinished);
};
}
private void waitForAngular() {
WebDriverWait wait = new WebDriverWait(driver, 15, 100);
wait.until(angularHasFinishedProcessing());
}
And here is the code that instantiates WebDriver for Internet Explorer.
System.setProperty("webdriver.ie.driver",
new File("H:/libraries/webdrivers/IEDriverServer.exe").getAbsolutePath());
DesiredCapabilities d = DesiredCapabilities.internetExplorer();
// To bypasse the Protected Mode settings of IE
d.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(d);
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://arandomangularjsapp.com"); // Let's suppose this
I had to bypass the Protected Mode settings (shown in above code) because I was constantly getting this Exception
Caused by: org.openqa.selenium.WebDriverException: Unexpected error launching Internet
Explorer. Protected Mode must be set to the same value (enabled or disabled) for all
zones. (WARNING: The server did not provide any stacktrace information)
though I made sure that protected mode was enabled and same values were set for all zones.
Now comes the real issue I am having. Look at this block of code,
waitForAngular();
WebElement el = driver.findElement(By.xpath("//div[#class='events-list__event-info' and #id='48040']" +
"//following-sibling::div[#class='events-list__event-buy']/a"));
if(driver.toString().toUpperCase().contains("INTERNETEXPLORER"))
el.sendKeys(Keys.ENTER);
else
el.click();
waitForAngular();
webElement = driver.findElement(By.xpath("(//div[#class='ticket u-cf ng-scope'])[1]//select"));
select = new Select(webElement);
select.selectByIndex(1);
My first question, the way I am trying to wait for Angular app to get ready by calling waitForAngular(), is it a good way? In my program I even had to use Thread.sleep() so many times in order to let elements to properly render before I could invoke actions on them. It would be great if you guys can suggest me a proper way to use Selenium WebDriver along with Angular App.
Now let's talk about my second issue. I had to completely disable Protected Mode from Internet Explorer's options in order to run the program. Otherwise, I would get this exception,
Caused by: org.openqa.selenium.JavascriptException: JavaScript error in async script. (WARNING: The server did not provide any stacktrace information)
I get this exception when trying to execute waitForAngular(). What could be causing this? Is there any way by which I could keep the Protected Mode enabled and still be able to execute that script inside angularHasFinishedProcessing() method?
Finally, my third problem is related to click action not being triggered. Forget about the previous issues for a second. I disabled IE's Protected Mode, so my program starts IE without throwing any exception. The program successfully finds the first element as shown in the code above. But, the click action is not triggered, browser thus doesn't navigate to next page, and the program fails to find the second element. As a workaround I even tried el.sendKeys(Keys.ENTER); but it didn't work.** So, am I having this problem because I bypassed/disabled Protected Mode? Or, is there something else that I am not being able to see?**
I run tests on IE, Opera, Chrome and Firefox and the problem seems to occur only in IE. Any sort of help, suggestions or guidelines are highly appreciated.
Thank You.

Ghostdriver 1.2.1 + PhantomJS 2.0 + latest Selenium Can't find variable error in Java

[ERROR - 2016-01-16T02:22:00.898Z] Session [e6651a90-bbf7-11e5-9061-cff578894101] - page.onError - msg: ReferenceError: Can't find variable: data
:262 in error
[ERROR - 2016-01-16T02:22:00.898Z] Session [e6651a90-bbf7-11e5-9061-cff578894101] - page.onError - stack:
(anonymous function) (http://www.example.com/ns/common/jquery/jquery.cartActions.js?cd=0:205)
o (http://www.example.com/images/common/jquery/jquery.latest.js:2)
fireWith (http://www.example.com/images/common/jquery/jquery.latest.js:2)
w (http://www.example.com/images/common/jquery/jquery.latest.js:4)
d (http://www.example.com/images/common/jquery/jquery.latest.js:4)
openUrl (:0)
open (:280)
(anonymous function) (:/ghostdriver/request_handlers/session_request_handler.js:495)
_execFuncAndWaitForLoadDecorator (:/ghostdriver/session.js:212)
_postUrlCommand (:/ghostdriver/request_handlers/session_request_handler.js:494)
_handle (:/ghostdriver/request_handlers/session_request_handler.js:91)
_reroute (:/ghostdriver/request_handlers/request_handler.js:61)
_handle (:/ghostdriver/request_handlers/router_request_handler.js:78)
:262 in error
^Domain edited out on purpose.
According to Can't find variable - PhantomJS this error has to do with not having proper jailed execution of Javascript. I don't understand what this means in the context of my Java program.
My Selenium program has only one kind of Javascript call, and it works like this:
((JavascriptExecutor) driver).executeScript("arguments[0].click();", buttonToClick);
The line above doesn't seem to be the issue because from my tests I can see that multiple lines like the above execute without error before coming to the above error.
Also, Session.NegotiatedCapabilities has "acceptSslCerts":false, which I have not been able to solve with this code block as the PhantomJS driver initializer:
String[] cli_args = new String[]{"--debug=false", "--web-security=false", "--ssl-protocol=any", "--ignore-ssl-errors=true"};
DesiredCapabilities caps = DesiredCapabilities.phantomjs();
caps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cli_args);
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/Users/richard/Downloads/phantomjs-2.0.0-macosx/bin/phantomjs");
driver = new PhantomJSDriver(caps);
I can see that the arguments ARE being passed in on the Console...
Jan 16, 2016 6:23:40 AM org.openqa.selenium.phantomjs.PhantomJSDriverService <init>
INFO: arguments: [--web-security=no, --ignore-ssl-errors=yes, --webdriver=33238, --webdriver-logfile=/Users/richard/YeezyBot/phantomjsdriver.log]
Finally, everything works with Firefox WebDriver.
Injecting JavaScript to the web page or any other element is poor practice. You can find the Element using Selenium code and click on it without the use of any injection.
Wait for the page to be loaded
Find the button by CSS or Xpath expression
Wait for the element to by clickable
click on it using Selenium code only
WebDriverWait wait = new WebDriverWait(driver, timeToWait);
this.by = by;
try {
webElement lastFoundElement =
wait.until(ExpectedConditions.visibilityOfElementLocated(by));
wait.until(ExpectedConditions.elementToBeClickable(lastFoundElement ));
new Actions(browser).moveToElement(element, offsetX, offsetY).click().build().perform();
}
catch (Exception ex)
{
}

selenium javascript - how to refer to the test runner window?

In my app, in the [firefox] browser javascript console I can do this:
elems=document.getElementsByTagName("a")[3]; elems.click();
and the 3rd anchor is clicked
How can I do that using the SeleniumIDE ?
I have a Test Case which does:
store
javascript{elems=document.getElementsByTagName("a")[3]; elems.click();}
dummy
but I just get the somewhat standard invalid javascript error of [error] Unexpected Exception: fileName -> chrome://selenium-ide/content/selenium-core/scripts/selenium-api.js, lineNumber -> 2535, columnNumber -> 0
I have also tried
javascript{elems=driver.document.getElementsByTagName("a")[3]; elems.click();}
and
javascript{elems=driver.getElementsByTagName("a")[3]; elems.click();}
but neither worked.
Have you tried this?
selenium.getEval("var window = this.browserbot.getUserWindow(); var elems = window.document.getElementsByTagName('a')[3]; elems.click();");

Categories