euclid135
euclid135

Reputation: 1272

Selenium Java inject new Javascript function

I have a dynamic function that I want to add after page loading. I need to do this because the function name depends on some variable that I get after parsing HTML. For now I've done this:

Spec: I'm using selenium 3.3.1 with PhantomJS 1.9.8

((JavascriptExecutor) driver).executeScript(" eval('function getVoteX1() { return 1; }')");
String testScript = (String)((JavascriptExecutor) driver).executeScript(" getVoteX1()");
System.out.println(testScript);

But when I run this, it throws error :

Caused by: org.openqa.selenium.WebDriverException: {"errorMessage":"Can't find variable: getVoteX1","request":{"

Note: Eventually, getVoteX1 will be replaced by some other variable, but for simplicity I tried a static name first.

Upvotes: 2

Views: 2519

Answers (1)

Javier
Javier

Reputation: 12398

Assign the new function to the window object, which is equivalent to defining a global variable:

((JavascriptExecutor) driver).executeScript("window.getVoteX1 = function() { return 1; }");
String testScript = (String)((JavascriptExecutor) driver).executeScript(" getVoteX1()");

Upvotes: 6

Related Questions