1

I'm trying to get the window object from a Selenium instance. I have the following code:

driver.executeScript(() => {
    return window;
})
.then(res => {
    console.log(res)
})

but this console res which is for some reason empty array: [].

vahdet
  • 6,357
  • 9
  • 51
  • 106
BT101
  • 3,666
  • 10
  • 41
  • 90

1 Answers1

4

Following the document of selenium, https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/JavascriptExecutor.html, driver.executeScript() only return below types of value:

  1. For an HTML element, this method returns a WebElement
  2. For a decimal, a Double is returned
  3. For a non-decimal number, a Long is returned
  4. For a boolean, a Boolean is returned
  5. For all other cases, a String is returned.
  6. For an array, return a List with each object, following the rules above. We support nested lists.
  7. For a map, return a Map with values following the rules above. Unless the value is null or there is no return value, in which null is returned

Which means it can't return window.

Instead of returning window object, I suggest to put all your javascript logic inside the executeScript method, then return any type of value as above. Then use that value in your code for other logic.

Robin Ding
  • 741
  • 6
  • 9
  • I tried but it is still giving null, can you check https://stackoverflow.com/questions/56073492/javascript-executor-gives-null-when-trying-to-access-window-propertyname – paul May 10 '19 at 13:31
  • @paul, seems you have found the solution. :) Please let me know if there is any other question. – Robin Ding May 14 '19 at 17:00
  • Nothing as of now, but in future if someone comes to this post might go disappointed. So, to avoid that could you please share working code? – paul May 14 '19 at 18:38