使用 Selenium WebDriver JavascriptExecutor 在单独的脚本中操作一个 JS 变量

Using Selenium WebDriver JavascriptExecutor to manipulate one JS variable in separate scripts

我需要达到以下场景:

1) 使用 JavascriptExecutor 初始化 JS var,它将指示是否完成了某些操作。

2) 对渲染器页面进行一些普通操作。

3) 验证对第 (1) 点中创建的 var 的更改。

例如:

jsc.executeScript("var test = false;");

现在,一些操作已经完成。 然后:

String testVal = jsc.executeScript("return test;").toString

我收到错误:

org.openqa.selenium.WebDriverException: {"errorMessage":"Can't find variable: test","request":{"headers":{"Accept":"application/json, image/png","Connection":"Keep-Alive","Content-Length":"35","Content-Type":"application/json; charset=utf-8","Host":"localhost:14025"},"httpVersion":"1.1","method":"POST","post":"{\"args\":[],\"script\":\"return test;\"}","url":"/execute","urlParsed":{"anchor":"","query":"","file":"execute","directory":"/","path":"/execute","relative":"/execute","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/execute","queryKey":{},"chunks":["execute"]},"urlOriginal":"/session/7e2c8ab0-b781-11e4-8a54-6115c321d700/execute"}}

当我运行他们在同一个执行中时,它工作正常。:

   String testVal = jsc.executeScript("var test = false; return test;").toString;

JavascriptExecutor doc 我找到了我需要的解释:

Within the script, use document to refer to the current document. Note that local variables will not be available once the script has finished executing, though global variables will persist.

我的alternative/workaround是什么?

不确定其背后的动机是什么,但您可以使用全局可用的 window 对象:

jsc.executeScript("window.test = false;");
String testVal = jsc.executeScript("return window.test;").toString

它也可能是 executeAsyncSript() 的用例,请参阅: