I have the following JavaScript code returning null
when ran through Selenium JavascriptExecutor
. However, the same code when ran in Firefox developer console returned a value.
function tmp(){
var attrb = jQuery(jQuery("[name='q']")[0]).attr('type');
if(typeof attrb !== 'undefined' && attrb !== false){
return attrb;
} else {
return '';
}
}
tmp();
The below is my WebDriver code with the JS the same as above:
JavascriptExecutor jsExec = (JavascriptExecutor)driver;
Object inpType =
jsExec.executeScript("function tmp(){...}tmp();");
System.out.println("Type: " + inpType);
Above outputs null
instead of "text" string. Any ideas?
To simplify the usage of JavascriptExecutor in Selenium, think of it as a medium that enables the WebDriver to interact with HTML elements within the browser. JavaScript is a programming language that interacts with HTML in a browser, and to use this function in Selenium, JavascriptExecutor is required.
JavaScriptExecutor is used when Selenium Webdriver fails to click on any element due to some issue. JavaScriptExecutor provides two methods “executescript” & “executeAsyncScript” to handle. Executed the JavaScript using Selenium Webdriver.
You should add a return
statement to the result you want to return from inside the jsExec.executeScript(...)
you need to use return tmp() instead of tmp() in executeScript() method. Find the related reference driver.executeScript() returns NullPointerException for simple javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With