2

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.

euclid135
  • 1,262
  • 2
  • 16
  • 23
  • Why would you `executeScript()` twice? Inject & evalute in a single step. Do as many operations you want within the script. – undetected Selenium Jan 15 '18 at 04:42
  • It is just a test. Because I'll need to run the script after some operations first, clicking here and there. But to make it simple, the flow will looks like that. And actually, my Java code would not run the getVoteX1, I just wanted to make sure that the function exists – euclid135 Jan 15 '18 at 05:51

1 Answers1

6

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()");
Javier
  • 12,100
  • 5
  • 46
  • 57