Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Javascript executor returns null

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?

like image 360
J28 Avatar asked Jul 28 '13 17:07

J28


People also ask

Why we use JavaScript executor in selenium?

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.

Why we write JavascriptExecutor JS JavascriptExecutor driver?

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.


2 Answers

You should add a return statement to the result you want to return from inside the jsExec.executeScript(...)

like image 162
Mohammad Noor Avatar answered Sep 28 '22 08:09

Mohammad Noor


you need to use return tmp() instead of tmp() in executeScript() method. Find the related reference driver.executeScript() returns NullPointerException for simple javascript

like image 27
Gangadhar Avatar answered Sep 28 '22 09:09

Gangadhar