How to scroll the window in Protractor (and a general introduction to executeScript())

By James Martin, published Friday, March 6th, 2015

Quite often when testing some functionality, you’ll want to scroll the page you’re looking at – particularly in Protractor, which yells at you if you try and interact with an element that isn’t physically inside of the viewport.

In this example, I am using jQuery, but feel free to use vanilla Javascript if you’re that way inclined.

Protractor, it self, does not have a way to scroll the page. This was an issue for me, since as I already alluded to, rather then just failing if it can’t click a button that isn’t visible, Protractor actively dies and won’t continue any further with the tests.

It turned out that the answer was fairly simple, but rather unituitive – you have to tell the browser to scroll the page for you.

This is where executeScript() comes in.

You can interact with the browser object in protractor, to perform actions with the underlying Selenium server that is actually doing all of the heavy lifting.

browser.executeScript() is a function that allows you to run snippets of Javascript on this, and it can actually be used for a few things.

Firstly, as the topic states, you can use it to scroll the window. Here’s how I achieved that:

browser.executeScript('$("body").scrollTop(1000);') //Note that your code is represented as a String here!         

It’s really that simple – that will call jQuery on the webpage, and make it scroll 1000 pixels from the top.

But that isn’t all you can use it for – you can also use it to query the page for information.

If you add ‘return’ before the code you want to execute, then the value of that is returned back into Protractor for use however you like.

As with almost everything else in Protractor, it’s handled like a promise:

browser.executeScript('return 1+1;').then(function(mathsIsFun){        

As I am sure you can imagine, this is an invaluable tool!

I wouldn’t go using this to do things like click elements or interact with the DOM though, that’s what Protractor is for afterall.

746176 753636I enjoy your writing style really enjoying this web site . 158948