Using Katalon to Run A Mobile Automated Test - mobile

I'm having issues running a simple log in, log out automated test using Katalon and Kobiton. Any time I run the script it gets stuck at the beginning and never runs. I'm trying to figure out what needs to be done for this to go through. Any help would be much appreciated.
As you can see below this is the code used and the resulting message received through Katalon.
Code:
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
Mobile.startApplication('kobiton', true)
Mobile.tap(findTestObject('android.widget.Button0 - ALREADY HAVE AN ACCOUNT'), 0)
Mobile.tap(findTestObject('android.widget.Button0 - ALREADY HAVE AN ACCOUNT'), 0)
Mobile.tap(findTestObject('android.widget.EditText0 - Email'), 0)
Mobile.setText(findTestObject('android.widget.EditText0 - Email (1)'), '', 0)
Mobile.setText(findTestObject('android.widget.EditText1 - Password'), '', 0)
Mobile.tap(findTestObject('android.widget.ImageView7'), 0)
Mobile.tap(findTestObject('android.widget.Switch0 - OFF'), 0)
Mobile.tap(findTestObject('android.widget.Button3 - LOGIN'), 0)
Mobile.tap(findTestObject('android.widget.Button0 - '), 0)
Mobile.tap(findTestObject('android.widget.TextView12 - Logout'), 0)
Mobile.closeApplication()
Message:
(Stack trace: com.kms.katalon.core.exception.StepFailedException: Unable to start app at: (Root cause: org.openqa.selenium.WebDriverException: org.apache.http.client.ClientProtocolException
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
System info: os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_181'
Driver info: driver.version: SwipeableAndroidDriver)
at com.kms.katalon.core.keyword.internal.KeywordMain.stepFailed(KeywordMain.groovy:36)
at com.kms.katalon.core.mobile.keyword.internal.MobileKeywordMain.stepFailed(MobileKeywordMain.groovy:40)
at com.kms.katalon.core.mobile.keyword.internal.MobileKeywordMain.runKeyword(MobileKeywordMain.groovy:23)
at com.kms.katalon.core.mobile.keyword.builtin.StartApplicationKeyword.startApplication(StartApplicationKeyword.groovy:51)
at com.kms.katalon.core.mobile.keyword.builtin.StartApplicationKeyword.execute(StartApplicationKeyword.groovy:40)
at com.kms.katalon.core.keyword.internal.KeywordExecutor.executeKeywordForPlatform(KeywordExecutor.groovy:53)
at com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords.startApplication(MobileBuiltInKeywords.groovy:74)
at com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords$startApplication.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at Script1541159043147.run(Script1541159043147.groovy:16)
at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:183)
at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:108)
at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:294)
at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:285)
at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:264)
at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:256)
at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:200)
at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:99)
at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:90)
at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:149)
at TempTestCase1541422340602.run(TempTestCase1541422340602.groovy:22)
at groovy.lang.GroovyShell.runScriptOrMainOrTestOrRunnable(GroovyShell.java:263)
at groovy.lang.GroovyShell.run(GroovyShell.java:518)
at groovy.lang.GroovyShell.run(GroovyShell.java:507)
at groovy.ui.GroovyMain.processOnce(GroovyMain.java:653)
at groovy.ui.GroovyMain.run(GroovyMain.java:384)
at groovy.ui.GroovyMain.process(GroovyMain.java:370)
at groovy.ui.GroovyMain.processArgs(GroovyMain.java:129)
at groovy.ui.GroovyMain.main(GroovyMain.java:109)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.groovy.tools.GroovyStarter.rootLoader(GroovyStarter.java:109)
at org.codehaus.groovy.tools.GroovyStarter.main(GroovyStarter.java:131)
)

You need to add real file.apk into the code
Mobile.startApplication('C:/user/...', true)
then you will success
You could find the APIdemos.apk file in this path
"C:\Users\username\Katalon Studio\NewTest1.prj\androidapp\APIdemos.apk"

This error generally occurs for cloud applications when path is not properly provided. Instead of 'kobiton', you need to provide the id or the storage path from kobiton for the application you have uploaded on their site.
For example:
Mobile.startApplication('kobiton-store:71', true)
or provide the path in capability as:
capabilities.SetCapability("app", "kobiton-store:71");

Related

Why some of the elements cannot be selected by Selenium webdriver?

I've been using Selenium webdriver for quite a while. Recently I came across this page: https://www.myagedcare.gov.au/service-finder
It seem very simple and I try to use id locator: bylocation
However, no matter how long I wait for the element to be ready by adding wait for some time, or wait for element to be ready like:
WebDriver driver = getDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(
ExpectedConditions.elementToBeClickable(By.id("byname")))
.click();
the element is never ready, and I always get error like "no such element: Unable to locate element:"
What might be going on? I've used locator for quite a while and I do not know how this can happen.
I am using chromedriver 2.30 and Chrome browser v.60.
A simple id locator like this in www.google.com does not give me any trouble. I tested it so that I do not think it's driver or browser issue.
Logs
net.serenitybdd.core.exceptions.SerenityWebDriverException: Timed out after 10 seconds waiting for visibility of element located by By.xpath: //input[#id='bylocation']
Build info: version: '2.46.0', revision: '61506a4624b13675f24581e453592342b7485d71', time: '2015-06-04 10:22:50'
System info: host: 'yun-PC', ip: '192.168.1.14', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_71'
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#id='bylocation']"}
(Session info: chrome=60.0.3112.50)
(Driver info: chromedriver=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 20.04 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Try this xpath and let me know if it works,
//div[#id='edit-search-by--2']//label[normalize-space(text())='Location']/preceding-sibling::input[#type='radio']
Also try waiting for visibility of element and not for element to be clickable.
Edit:
The above Xpath is perfect. Problem was that the element was located in a frame.
Below code will get you going with the click part:
driver.get("https://www.myagedcare.gov.au/service-finder?tab=help-at-home");
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[#id='content']")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[#id='content']")));
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//label[normalize-space(text())='Location']/preceding-sibling::input[#type='radio']")));
WebElement location = driver.findElement(By.xpath("//label[normalize-space(text())='Location']/preceding-sibling::input[#type='radio']"));
WebElement name = driver.findElement(By.xpath("//label[normalize-space(text())='Name']/preceding-sibling::input[#type='radio']"));
location.click();
Thread.sleep(3000);
name.click();
driver.switchTo().parentFrame();
Click working video - https://www.screencast.com/t/0Fsw7gGZ
As the Radio Buttons are inside input tags, instead of id use xpath locator as follows:
WebDriverWait wait6 = new WebDriverWait(driver, 10);
WebElement radio_name = wait6.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#id='byname']/input[#id='byname']")));
radio_name.click();
Let me know if this Answers your Question.

a error occur in remoteDriver function of RSelenium

I want to scrape data on dynamic web by the following code:
> URL<- "http://www.cbooo.cn/realtime"
> library(bitops)
> library(RCurl)
> library(XML)
> library(RSelenium)
> library(magrittr)
> checkForServer()
Warning message:
checkForServer is deprecated.
Users in future can find the function in file.path(find.package("RSelenium"), "example/serverUtils").
The sourcing/starting of a Selenium Server is a users responsiblity.
Options include manually starting a server see vignette("RSelenium-basics", package = "RSelenium")
and running a docker container see vignette("RSelenium-docker", package = "RSelenium")
> startServer()
$stop
function ()
{
tools::pskill(selPID)
}
<environment: 0x10991af0>
$getPID
function ()
{
return(selPID)
}
<environment: 0x10991af0>
Warning message:
startServer is deprecated.
Users in future can find the function in file.path(find.package("RSelenium"), "example/serverUtils").
The sourcing/starting of a Selenium Server is a users responsiblity.
Options include manually starting a server see vignette("RSelenium-basics", package = "RSelenium")
and running a docker container see vignette("RSelenium-docker", package = "RSelenium")
> remDrv <- remoteDriver()
> remDrv$browserName="Internet Explorer"
> remDrv$open()
[1] "Connecting to remote server"
Selenium message: The best matching driver provider org.openqa.selenium.ie.InternetExplorerDriver can't create a new driver instance for Capabilities [{nativeEvents=true, browserName=Internet Explorer, javascriptEnabled=true, version=, platform=ANY}]
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'DESKTOP-J0D980N', ip: '10.36.17.76', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_77'
Driver info: driver.version: unknown
Error: Summary: UnknownError
Detail: An unknown server-side error occurred while processing the command.
class: org.openqa.selenium.WebDriverException
Further Details: run errorDetails method
There are the following questions which I can't solve:
1 checkForServer,startServer are deprecated.
2 connecting to remote server always fials,I don't konw how to set some argurment in this funciotn and what should be done
I hope to get a anwser as soon as possible ,thanks.
The author of RSelenium provides a solution as following (https://github.com/ropensci/RSelenium/issues/81):
From Firefox 48 on-wards the gecko driver/ marionette will be needed to run Firefox with Selenium.
If you have Firefox 48 you can run the gecko driver as follows:
Refer to the guidelines
https: //developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver
Download the relevant gecko driver from
https: //github.com/mozilla/geckodriver/releases
Add it to your PATH or refer to the location when starting binary (see below)
# get beta selenium standalone
RSelenium::checkForServer(beta = TRUE)
# assume gecko driver is not in our path (assume windows and we downloaded to docs folder)
# if the driver is in your PATH the javaargs call is not needed
selServ <- RSelenium::startServer(javaargs = c("- Dwebdriver.gecko.driver=\"C:/Users/john/Documents/geckodriver.exe\""))
remDr <- remoteDriver(extraCapabilities = list(marionette = TRUE))
remDr$open()
....
....
remDr$close()
selServ$stop()
Well to produce a viable working solution I would use the old version of RSelenium and everything with this code.
if (!require("XML")) {
install.packages("XML",repos= 'https://cloud.r-project.org')
library("XML")
}
#XML is a dependency
if (!require("RSelenium")) {
install.packages("https://cran.r-project.org/src/contrib/Archive/RSelenium/RSelenium_1.3.5.tar.gz", repos=NULL, type="source", dependencies = TRUE)
library("RSelenium")
}
download.file('http://selenium-release.storage.googleapis.com/2.53/selenium-server-standalone-2.53.1.jar', destfile = "~/Documents/R/library/RSelenium/bin/selenium-server-standalone.jar")
#start server
system('java -jar "~/Documents/R/library/RSelenium/bin/selenium-server-standalone.jar"')
library(RSelenium)
checkForServer()
startServer()
That is not an optimal solution. But a working solution.

Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died

I tried to execute this Selenium Script,
public class FirePath_Ex {
public static void main(String[] args)
{// TODO Auto-generated method stub
WebDriver d=new FirefoxDriver();
d.get("https://facebook.com");
d.findElement(By.xpath(".//*[#id='email']")).sendKeys("dhhfdssd");
d.findElement(By.id("pass")).sendKeys("sjfsdfj");
}
}
it shows the error below after closing FireFox,
Exception in thread "main"
org.openqa.selenium.remote.UnreachableBrowserException: Error
communicating with the remote browser. It may have died.
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 02:56:46'
System info: host: 'Admin-PC', ip: '192.168.0.101', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version:
'1.7.0-ea'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:589)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:348)
at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:445)
at org.openqa.selenium.By$ByXPath.findElement(By.java:358)
at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:340)
at FirePath_Ex.main(FirePath_Ex.java:13)
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to 127.0.0.1:7055 [/127.0.0.1] failed: Connection refused: connect
How do I resolve this?
Try to add this below code and replace the path of firefox exe with your absolute path:-
System.setProperty("webdriver.firefox.bin", "C:\\firefox.exe");
So your code should be like:-
public class FirePath_Ex {
public static void main(String[] args)
{// TODO Auto-generated method stub
System.setProperty("webdriver.firefox.bin", "C:\\firefox.exe");
WebDriver d=new FirefoxDriver();
d.get("https://facebook.com");
d.findElement(By.xpath(".//*[#id='email']")).sendKeys("dhhfdssd");
d.findElement(By.id("pass")).sendKeys("sjfsdfj");
}
}
Hope it will help you :)
This was driving me crazy for quite a bit.
For me, simply re-instantiating it solved the problem some of the time. (like below). However, 95% of the time it's because my selenium version is not compatible with the firefox version. The documentation for supported version is not easy to parse, nor does it contain an exhaustive list. Sometimes it takes some trail and error.
public FirefoxWebPageReader firefoxWebPageReader() {
return forceInit(3);
}
private FirefoxWebPageReader forceInit(final int tries) {
if (tries == 0) {
throw new RuntimeException("Can not initialize Firefox reader");
}
try {
final String binaryPath = environment.getProperty("crawler.firefox.path");
return new FirefoxWebPageReader(binaryPath);
} catch (WebDriverException e) {
LOGGER.error("Error occurred when building FirefoxWebPageReader, tries left: " + (tries - 1), e);
return forceInit(tries - 1);
}
}
The probable reason may be the incompatibility between the browser and the chromedriver, so installing the updated chromedriver or updating chrome might help

" StaleElementReferenceException: Element is no longer attached to the DOM " issue while running script. (Firefox browser)

My requirement is
Get all data from grid
Search specific text, if found
Click check box
My code is,
List<WebElement> totalRows = driver.findElements(By.xpath("//*[#id='ContentPlaceHolder1_ContentPlaceHolderChild_grdGroupSelection']/tbody/tr"));
System.out.println("Total Size: "+totalRows.size());
for (int count=1;count<totalRows.size()-1;count++){
System.out.println("Loop count: "+count);
WebElement rowElement = totalRows.get(count);
System.out.println("WebElement Tag name: "+rowElement.getTagName());
}
Unable to get the value from rowElement.
Here posted Logs, HTML source & snapshot for reference. Please help me out. Thanks in advance.
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
Command duration or timeout: 294 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.43.1', revision: '5163bce', time: '2014-09-10 16:27:33'
System info: host: 'Saravanan-PC', ip: '192.168.101.22', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Session ID: 6ea5596b-9f0f-477b-9a11-dc534a0197ee
Driver info: org.openqa.selenium.firefox.FirefoxDriver
Capabilities [{platform=WINDOWS, databaseEnabled=true, cssSelectorsEnabled=true, javascriptEnabled=true, acceptSslCerts=true, handlesAlerts=true, browserName=firefox, webStorageEnabled=true, nativeEvents=false, rotatable=false, locationContextEnabled=true, applicationCacheEnabled=true, takesScreenshot=true, version=35.0.1}]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:187)
at org.openqa.selenium.remote.RemoteWebElement.findElementsByTagName(RemoteWebElement.java:264)
at org.openqa.selenium.By$ByTagName.findElements(By.java:323)
at org.openqa.selenium.remote.RemoteWebElement.findElements(RemoteWebElement.java:163)
at com.aetherpal.scripts.ClientPolicyProfiles.selectCreatedCSPGroupID(ClientPolicyProfiles.java:95)
at com.aetherpal.scripts.ClientPolicyProfiles.main(ClientPolicyProfiles.java:80)
Caused by: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.43.1', revision: '5163bce', time: '2014-09-10 16:27:33'
System info: host: 'Saravanan-PC', ip: '192.168.101.22', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.7.0_51'
Driver info: driver.version: unknown
at .fxdriver.cache.getElementAt(resource://fxdriver/modules/web-element-cache.js:8325:24)
at .Utils.getElementAt(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:7922:10)
at .FirefoxDriver.prototype.findElementsInternal_(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:9636:32)
at .FirefoxDriver.prototype.findChildElements(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/driver-component.js:9657:3)
at .DelayedCommand.prototype.executeInternal_/h(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:11612:16)
at .DelayedCommand.prototype.executeInternal_(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:11617:7)
at .DelayedCommand.prototype.execute/<(file:///C:/Users/SARAVA~1/AppData/Local/Temp/anonymous631926879527649788webdriver-profile/extensions/fxdriver#googlecode.com/components/command-processor.js:11559:5)
Grid:
HTML Source:
The checkbox, ID and the GroupName will be inside the tr.
Checkbox is the only input element inside the tr. You can use the following code which will wait for the checkbox of particular GroupName(in your case ACL all) to appear and click on it as soon as it is visible.
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(20));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//table[#id='ContentPlaceHolder1_ContentPlaceHolderChild_grdGroupSelection']//td[text()='ACL all']/..//input")));
element.Click();
The webpage might keep changing due to various reasons ie Reloading/Etc which are not very visible ,
Approach 1 :
One approach to this stale element exception is Trying to reduce the time between 'Find element' and 'Do some action on element'
Approach 2 :
Have a Repeated while loop to check the availablity of element until some condition is true , Also make sure to use Implicit/Explicit/Fluent waits , it helps a lot but never do a thread.sleep .
Finally I tried with JavascriptExecutor.executeScript() method. Its working fine...I don't know whether this approach is correct way or not..
my sample code is,
JavascriptExecutor scriptExecute = (JavascriptExecutor)driver;
WebElement el = (WebElement) scriptExecute.executeScript("var noOfRows =document.querySelectorAll('table[id=ContentPlaceHolder1_ContentPlaceHolderChild_grdGroupSelection]>tbody>tr'); " +
"for(var i=1;i<noOfRows.length-1;i++){" +
"return noOfRows[i]; }");
el.click();

PhantomJSDriver (GhostDriver) can't get localStorage values using javascript

Using PhantomJsDriver (GhostDriver) for testing my web application.
Trying to access the local storage values using calls like:
(String) js.executeScript(String.format("return localStorage.getItem('%s');", key));
In webDriver initialisation I'm setting the capability:
DesiredCapabilities dCaps = new DesiredCapabilities()
dCaps.setJavascriptEnabled(true)
dCaps.setCapability("webStorageEnabled", true)
return new PhantomJSDriver(dCaps)
Receiving WebDriverException while trying to execution the JS above, from which it looks like the webStorageEnabled have been never set to true:
org.openqa.selenium.WebDriverException: {"errorMessage":"SECURITY_ERR:
DOM Exception 18","request":{"headers":{"Accept":"application/json,
image/png","Connection":"Keep-Alive","Content-Length":"98","Content-Type":"application/json;
charset=utf-8","Host":"localhost:20884"},"httpVersion":"1.1","method":"POST","post":"{\"args\":[],\"script\":\"return
localStorage.getItem('cartId_136d7735-13d7-8178-8abf-010beb62f8cf');\"}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/5f67ce30-310a-11e4-83c7-6d52cfce6b64/execute"}}
Command duration or timeout: 8 milliseconds Build info: version:
'2.39.0', revision: '14fa800511cc5d66d426e08b0b2ab926c7ed7398', time:
'2013-12-16 13:18:38'
Driver info: org.openqa.selenium.phantomjs.PhantomJSDriver
Capabilities [{platform=MAC, acceptSslCerts=false,
javascriptEnabled=true, browserName=phantomjs, rotatable=false,
driverVersion=1.1.0, locationContextEnabled=false, version=1.9.7,
cssSelectorsEnabled=true, databaseEnabled=false, handlesAlerts=false,
browserConnectionEnabled=false, webStorageEnabled=false,
nativeEvents=true, proxy={proxyType=direct},
applicationCacheEnabled=false, driverName=ghostdriver,
takesScreenshot=false}] at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
What could be the reason for the issues I experiencing? Should it be possible to set webStorageEnabled for PhantomJSDriver? If no, how can I work around this issue?
It looks like it's still not implemented:
https://github.com/detro/ghostdriver/blob/6c918e230cc98a7bce75e652c020c55cc3e0dd23/src/session.js#L65
https://github.com/detro/ghostdriver/issues/25
After some thinking I have managed to solve this issue.
In general, it's possible to access localStorage using using JavaScript. The issue described here happened because of something else.
Here is the flow I had:
1) Initialize WebDriver
2) Access localStorage
3) Doing driver.get(url)
The problem is, driver.get(url) must happen before accessing localStorage. That solved the issue.
Here is my LocalStorage driver implementation (in Scala), if you need one: LocalStorageDriver

Resources