Can not Execute JavaScript command using Selenium WebDriver in C# - javascript

I can not execute js command using selenium web driver. for example, I used 3 ways for this URL but all of them return null.
web.FindElementByJs("StackExchange.init.length");
IJavaScriptExecutor js = (IJavaScriptExecutor)web;
string title = (string)js.ExecuteScript("StackExchange.init.length");
web.ExecuteJavaScript("StackExchange.init.length");

I get it!
For an object, I should use 'window'.
IJavaScriptExecutor js = (IJavaScriptExecutor)web;
string title = (string)js.ExecuteScript("return window.StackExchange.init.length");

Related

What does execute_script() in Selenium does

browser.execute_script("window.open('about:blank', 'tab2');")
browser.switch_to.window("tab2")
browser.get('http://bing.com')
I was searching online ways to open a new tab using selenium in python, and the method of ctrl + t wasn't working on chrome so I stumbled on the above piece of code, however I am not able to understand what 'excute_script' does.
execute_script method allows to execute JavaScript passed as string argument
Note that you can pass data from Python code into JavaScript code using arguments, e.g.
hello = "Hello"
friends = " friends"
browser.execute_script('alert(arguments[0], arguments[1]);', (hello, friends))
execute_script()
execute_script() synchronously executes JavaScript in the current window/frame.
execute_script(script, *args)
where:
script: The JavaScript to execute
*args: Any applicable arguments for your JavaScript.
This method is defined as:
def execute_script(self, script, *args):
"""
Synchronously Executes JavaScript in the current window/frame.
:Args:
- script: The JavaScript to execute.
- \\*args: Any applicable arguments for your JavaScript.
:Usage:
::
driver.execute_script('return document.title;')
"""
if isinstance(script, ScriptKey):
try:
script = self.pinned_scripts[script.id]
except KeyError:
raise JavascriptException("Pinned script could not be found")
converted_args = list(args)
command = None
if self.w3c:
command = Command.W3C_EXECUTE_SCRIPT
else:
command = Command.EXECUTE_SCRIPT
return self.execute(command, {
'script': script,
'args': converted_args})['value']
Examples
A couple of examples:
To open a new blank tab:
driver.execute_script("window.open('','_blank');")
To open a new tab with an url:
driver.execute_script("window.open('https://www.google.com');")
To retrieve the page title:
driver.execute_script('return document.title;')
To scroll inti view an element:
driver.execute_script("arguments[0].scrollIntoView(true);",element)
References
You can find a couple of relevant detailed discussions in:
What does arguments[0] and arguments[1] mean when using executeScript method from JavascriptExecutor interface through Selenium WebDriver?
What is JavaScriptExecutor in Selenium?

Extract and Store javascript variable value inside script written inside executeScript to normal java variable

In below-written code, I want to use the URL variable value inside the javascript written and I want to store it in String URL variable of java.
I tried to use the getParameter method but that is used in JSP. I tried to Search it elsewhere but everywhere the value extraction is explained through JSP. Please help. Is there any way other than JSP for using the value inside the script?
System.setProperty("webdriver.chrome.driver","F:\\Browser Chrome Driver files\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
//WebDriver driver1 = null;
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("var url = prompt(\"URL\");");
String url = request.getParameter("url");
2nd attempt:
When I use this code,
System.setProperty("webdriver.chrome.driver","F:\\Browser Chrome Driver
files\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
//WebDriver driver1 = null;
JavascriptExecutor js = (JavascriptExecutor)driver;
//String script = ;
String url =(String)js.executeScript("var user = prompt(\"Enter your
name, please:\", \"https://myeg/login\");\r\n" +
"if (user != null) {\r\n" +
" return user;\r\n" +
"}");
Thread.sleep(5000);
driver.get(url);
I am getting Exception in thread "main" java.lang.NullPointerException: null value in entry: url=null. I want the URL to be accessed by the driver through javascript prompt. But getting null pointer exception on 2nd attempt.
You can use return in the JavaScript
String script = "var url = prompt(\"URL\");"
+ "return url;";
String url = (String)js.executeScript(script);
I found the solution myself. I used java and succeeded. I imported javax.swing.JOptionPane library and created object of JOptionPane class. Then used showInput dialog method and I stored the value I put in that dialog in a variable. It worked.

How to check firefox console output with Selenium/javascript?

When I enter the following command into the firefox console I get 65. This is the number I want to check with selenium.
$('#grid').data('kendoGrid').dataSource.total()
Is there anyway I can get selenium to check this?
I have tried the following,
To test out javaScript, (this correctly checks title),
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string title = (string)js.ExecuteScript("return document.title");
Console.Write(var);
I have tried, both failed.
String num = (String)((IJavaScriptExecutor)driver).ExecuteScript("$('#grid').data('kendoGrid').dataSource.total()");
Console.Write(num);
&
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
String script = "$('grid').data('kendoGrid').dataSource.total()";
String num = (String)js.ExecuteScript("return", script);
Console.Write(num);
I'm just using Console.Write to see the output.

How to get javascript tooltip message in Selenium?

I want to get a tool tip message which appear when mouse hover over an icon. I want to get the message in Selenium gettext() method and assign it to a String.
Below is my code:
JavascriptExecutor jse = (JavascriptExecutor)driver;
String script = "return driver.findElement(By.xpath(ObjectRepository.tooltipMsg)).getText();";
String message = ((JavascriptExecutor) driver).executeScript(script).toString();
Thread.sleep(3000);
System.out.println("message "+message);
This is not working and I'm getting the error driver is not defined
Error driver is not defined is thrown because of the below statement.
return driver.findElement(By.xpath(ObjectRepository.tooltipMsg)).getText();
This is actually not a Javascript, but a Java code to find the text of the webelement. Hence, driver defined in java cannot be used as such while creating a javascript.
Using Javascript:
String script = "return document.getElementById("your-id").innerHTML;";
String message = ((JavascriptExecutor) driver).executeScript(script).toString();
Using Java:
String message = driver.findElement(By.xpath("your XPath")).getText();
You need to provide the correct XPath or Id above to find the element. Let me know if you have any queries.
first, you need define your drvier:
WebDriver driver = new FirefoxDriver();
later, you can get attribute of element has tooltip
String message = driver.findElement(By.xpath("ObjectRepository.tooltipMsg")).getAttribute("title");

How to get a return value from IJavaScriptExecutor

I am using Selenium WebDriver (.net) and have an IJavaScriptExecutor that I call .ExecuteScript on. I want it to return a value to me, but I can't seem to get it to do so.
string displayedCallNumber = (string) _driver.JavaScript.ExecuteScript("return $('#CallNumberSearch').val();");
I can use jQuery as the page that I am using has jQuery automatically. What am I doing wrong?
P.S. $('#CallNumberSearch').val(); works when I am in the browser w/o Selenium
You could try:
JavascriptExecutor js = (JavascriptExecutor)driver;
String str = js.executeScript("script");

Categories