1

Using Selenium Java bindings.

I'm trying to write a short module that will take a full screenshot of a browser page (I know AShot exists but it is not maintained and has some issues for me).

As part of this I would like to know what the full page length is that I'm dealing with so I can calculate the number of shots I need to take, and any remainder at the bottom. There are many examples out there showing how to scroll to the bottom of a page (e.g. this question), but I am wondering if there is a way to make the JavascriptExecutor return the value of the page length so I can use it in my script?

Hester Lyons
  • 803
  • 11
  • 24

1 Answers1

2

You need the scrollHeight

JavascriptExecutor js = (JavascriptExecutor) driver;         
js.executeScript("return document.documentElement.scrollHeight");

After looking further for a more robust solution, this Javascript-code (which I took from the same website) should provide a better result:

let scrollHeight = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight,
  document.body.clientHeight, document.documentElement.clientHeight
);

return scrollHeight;
Tim Hansen
  • 84
  • 2
  • 14
  • It was the `return` statement in JS that I didn't realise you could use - my JS is rudimentary to say the least. This will come in very useful in general, I think. Thanks again. – Hester Lyons May 16 '19 at 08:41
  • 1
    I wasn't sure what the main focus of your question was, but I am happy it helped. You should be able to cast the return of .executeScript as a String and then go from there. – Tim Hansen May 16 '19 at 08:43
  • I would cast it as a number (`long` I think?) and use it that way instead of a string. – JeffC May 16 '19 at 14:44
  • @JeffC: In my personal experience Selenium behaves weird sometimes and directly casting to a numerical value could have you running into an exception. String should always work and you can double check on the Java side. That was my thinking behind it, but heck, no risk, no fun. – Tim Hansen May 16 '19 at 14:46