Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a JavaScript function from within Selenium?

I need to call a JavaScript function from Selenium WebDriver in Firefox. I use this command in Firebug's Command Editor to invoke a file upload application after logged into my website:

infoPanel.applicationManager.changeApp('FileUploader', {action: 'new'})

Is there a way to execute this from Selenium?

like image 241
bpk Avatar asked Nov 21 '14 09:11

bpk


People also ask

How do you call a function in Selenium?

To access any Selenium WebDriver methods, first, we need to create a driver object using a WebDriver reference variable and then all the public methods will appear for that object. Thus, we can call Selenium WebDriver methods using an object reference variable.

Can Selenium interact with Javascript?

Selenium is an open-source automation testing tool that supports a number of scripting languages like C#, Java, Perl, Ruby, JavaScript, etc.

Which Selenium code can execute Javascript directly?

a) executeScript This method executes JavaScript in the context of the currently selected window or frame in Selenium.


2 Answers

Try this:

WebDriver driver = new ChromeDriver();
((JavascriptExecutor)driver).executeScript("yourScript();");
like image 129
Sergii Tanchenko Avatar answered Oct 13 '22 00:10

Sergii Tanchenko


WebDriver driver = new AnyDriverYouWant();

if (driver instanceof JavascriptExecutor)

{

((JavascriptExecutor)driver).executeScript("yourScript();");

}
like image 44
Helping Hands Avatar answered Oct 13 '22 01:10

Helping Hands