javascript executor gives null when trying to access window.propertyname - javascript

I can see these many properties in console if I type window in Chrome console and hit enter.
But when I am trying to access same properties via Javascript Executor it gives me null.
I tried:
String homepage = jse().executeScript("window.origin", "found homepage").toString();
System.out.println("home page is "+homepage);
and
String location = "function show_homepage() {var homepage = window.location.origin;return homepage;}"
String homepage = jse().executeScript(location, "found if email validated or not").toString();
System.out.println("Answer is "+homepage);
Reference:
window object from selenium webdriver is empty array
https://www.softwaretestingmaterial.com/javascriptexecutor-selenium-webdriver/
View list of all JavaScript variables in Google Chrome Console

I found the solution. The mistake I was doing, I was not returning function in JS snippet. I added one more line return show_homepage(); and it worked.
String location = "function show_homepage() {"+
"var homepage = window.location.origin;"+
"return homepage;"+
"}"+
"return show_homepage();";
Object str = js().executeScript(location, "");
System.out.println(str.toString());

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.

Adobe Javascript Signature Lock

I am trying to use Adobe Javascript to change the properties of a fillable form text box when a signature is added to a signature block.
A PDF file is created by exporting from Excel into PDF.
An Action is then used to Detect Form Fields which produces 2 text boxes and 2 signature blocks automatically.
The Action then runs this:
var f =this.getField("Signature").required = true ;
to make the first signature block a required form.
Everything is successful up to this point.
The action then attempts to run this:
var f =this.getField("Signature");
var oLock = f.getLock();
oLock.action = "include";
oLock.fields = new Array("Receivers CommentsRow1");
f.setLock(oLock);
Which throws up the error
TypeError: oLock is null
4:Batch:Exec
Running directly from the console gives the same error.
Any help is appreciated, thanks.
According to the documentation http://help.adobe.com/en_US/acrobat/acrobat_dc_sdk/2015/HTMLHelp/Acro12_MasterBook/JS_API_AcroJS/Field_methods.htm?rhtocid=_6_1_8_31_2_12#TOC_getLockbc-13
oLock.action = "include";
"include" should be initial caps "Include".

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

Categories