1

I am trying to execute a javascript function from java code.

I used JavascriptExecutor from selenium package.

I tried below code

  JavascriptExecutor js;
  js.executeScript("let time;");
  js.executeScript("time = 2;");
  js.executeScript("function f(){console.log(time);}");
  js.executeScript("f()");

This is output

Exception in thread "Thread 0" 
org.openqa.selenium.JavascriptException: javascript error: f is not defined

Is there any way to execute the above script from java code? is it possible?

M. Prokhorov
  • 3,894
  • 25
  • 39
samk
  • 410
  • 5
  • 13
  • Have a look at https://stackoverflow.com/questions/22856279/call-external-javascript-functions-from-java-code – i.bondarenko Oct 17 '19 at 14:06
  • @i.bondarenko Thanks. but I want to know if it's possible with JavaScriptExecutor method – samk Oct 17 '19 at 14:23
  • 1
    Each time you call `executeScript` it creates a *separate* script. You must put all those lines into the same call, so they can see results of each other. – M. Prokhorov Oct 17 '19 at 14:40
  • @M.Prokhorov but from the above snippet, 'time' variable is getting recognized even though they are separate scripts. Is there any explanation for that? – samk Oct 17 '19 at 15:07
  • @SameerKhan, how do you know it's recognized, since you never print it? `myvariable = 1` is valid javascript on it's own, it means global variable assignment, and creates the variable it not present already, unless in strict mode (which you aren't). – M. Prokhorov Oct 17 '19 at 15:14

2 Answers2

1

Try this:

String script = "let time;time = 2;function f(){console.log(time);}f()";
JavascriptExecutor js;
js.executeScript(script);
  • I have a use case where I have to use two different lines of executeScript. Is there any other way to do it? – samk Oct 17 '19 at 15:09
  • You could try to inject your script into the DOM using document.write... "" (I've never tried this myself.) So your first call to execute script executes a script that injects a script. Not sure why you wouldn't just put all of it in one string though. – pcalkins Oct 17 '19 at 19:47
1

You can use window properties (or any built-in really) which will stick around:

js.executeScript("window.time = 4");
js.executeScript("window.f = () => console.log(window.time)");
js.executeScript("window.f()");
pguardiario
  • 53,827
  • 19
  • 119
  • 159