0

I need to open an url using Selenium and execute a script. After sometime on 'Escape' keypress I need to pass value back to Java program.

My Java program.

JavascriptExecutor js = (JavascriptExecutor) driver;
String content = new String(Files.readAllBytes(Paths.get("xp_simple.js")));
String str = (String) js.executeScript(content);
System.out.println("Returned from js : " + str);

My passed javascript string.

var pageName='value from webpage';
window.addEventListener('keydown', function (zEvent) {
    if (zEvent.key === 'Escape') {
    console.log("Escape is pressed");
    return getSG()
     }
} );
function getSG() {
        return pageName;
};

Issue --> Control doesn't stay until Escape key is pressed. It immediately returns back to java program with str value as null.

Amresh
  • 315
  • 1
  • 5
  • 14

1 Answers1

0

The following code worked.

String content = new String(Files.readAllBytes(Paths.get("xpo_simple.js")));
String str = (String) js.executeAsyncScript(content);

JavaScript code

var pageName='value from webpage';
var callback=arguments[arguments.length - 1];

window.addEventListener('keydown', function (zEvent) {
    if (zEvent.key === 'Escape') {
    console.log("Escape is pressed");
        callback(getSG());
     }
} );
function getSG() {
        return pageName;
};
Dharman
  • 30,962
  • 25
  • 85
  • 135
Amresh
  • 315
  • 1
  • 5
  • 14