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

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();");

Related

How to trigger `undefined is not a function` in modern broswers?

I remember getting this error a lot a while before. Today I wanted to show it to a friend unfamiliar with Javascript. Chrome and Safari instead gave me something like:
> const o = {};
< undefined
> o.doge()
< TypeError: o.doge is not a function (In 'o.doge()',' 'o.doge' is undefined)
Chrome and Firefox seem to be user-friendly as well.
How can I get an original error, without this helpful message?
You will never get that error in a modern browser; the error comes from js engine itself not the browser; and if there are no others other than that Type Error, modern engines will return a more developer friendly error by applying a (similar) /(w+)/ regex on what ever typed before () and placing it in the error message check out:
v8 (chrome) message templates that will make the error string (line 51, 52):
T(CalledNonCallable, "% is not a function")
and SpiderMoneky (mozilla) message templates (at line 51, 54):
MSG_DEF(JSMSG_NOT_FUNCTION, 1, JSEXN_TYPEERR, "{0} is not a function")
non-callable test case in v8 and a SpiderMokney test case .
So the only way to a undefined is not a function error message in a modern browser is doing undefined() :)
undefined()
you can just try to find and download an older version of the browser which logged the original error. (if that version is still publicly available).

1 Uncaught SyntaxError: Unexpected end of JSON input

I have a site that randomly throws this JavaScript error. If you refresh the site it almost always occurs and it prevents the site from loading. Instead, you just see a blank white page.
The console states there is an "Uncaught SyntaxError: Unexpected end of JSON input" in require.js on line 8. The line reads:
html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
Is there something wrong with this line that I'm not seeing?
The site
Chrome console output
Firefox console output
define("lib/config", [], function() {
"use strict";
var e = document.getElementById("app-config");
return e ? JSON.parse(e.innerHTML) : {}
})
That's the problematic section of code. the app-config element isn't always loaded before this part is being executed. If possible, hard code your app-config into your html

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)
{
}

Android - Click on webpage link with Javascript

I'm developing an app which has to:
Open a webpage in a Webview;
Check the available links and click on the link which contains a certain word (I.e. http://www.domain.com/myword); after the click, the link will open in the same webview.
I tried the following code but it' giving this error "E/Web Console(6169): Uncaught SyntaxError: Unexpected identifier at null:1".
WebSettings myBrowserSettings = myBrowser.getSettings();
myBrowserSettings.setJavaScriptEnabled(true);
Log.d("Stefano", "JS enabled");
myBrowser.loadUrl("javascript:document.getElementsByTagName('a[href*='myWord']')[0].click();");
Can you help me?
Consider that I'm using document.getElementsById('My ID') in another part of the app (to click a button) and it's working correctly; but here, i'm not able to get getElementsByTagName working.
Thanks for your time and availability
UPDATE:
I replaced 'a[href*='myWord']' with \"a[href*='myWord']\" as suggested by the user but now i have this error E/Web Console(2683): Uncaught TypeError: Cannot call method 'click' of undefined at null:1.
Any idea?
'a[href*='myWord']'
This reads as string 'a[href*=', var myWord, string ']'
Presumably, you are trying to do this:
\"a[href*='myWord']\"

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

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':{}}\"")

Categories