javascript executor在尝试访问window.propertyname时给出null

时间:2019-05-10 08:22:03

标签: javascript google-chrome browser

如果我在Chrome控制台中输入window并按Enter,则可以在控制台中看到许多属性。

但是当我尝试通过Javascript Executor访问相同的属性时,它却为空。

我尝试过:

String homepage = jse().executeScript("window.origin", "found homepage").toString();
System.out.println("home page is  "+homepage);

String location = "function show_homepage() {var homepage = window.location.origin;return homepage;}"
String homepage = jse().executeScript(location, "found if email validated or not").toString();
System.out.println("Answer is "+homepage);

参考:

  1. window object from selenium webdriver is empty array
  2. https://www.softwaretestingmaterial.com/javascriptexecutor-selenium-webdriver/
  3. View list of all JavaScript variables in Google Chrome Console

enter image description here

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我正在做的错误是,我没有在JS代码段中返回函数。我又添加了一行return show_homepage();,它行得通。

String location = "function show_homepage() {"+
            "var homepage = window.location.origin;"+
            "return homepage;"+
            "}"+
            "return show_homepage();";
Object str = js().executeScript(location, "");
System.out.println(str.toString());