0

I'm creating some Selenium tests in JavaScript. I'm having trouble clicking on a button that is not in view (this seems to be an issue with the chrome driver). A workaround to this problem is simply scrolling to the element, however the examples shown are in Java, not JavaScript. Based on the solutions for java I tried the following without success:

    var element = driver.findElement(webdriver.By.id('next_button'));
    var location = element.getLocation();
    var window = new webdriver.Window(driver);
    window.scrollBy(location);

I don't think I'm using the right type of window object here. How do I scroll down to the element using JavaScript?

Community
  • 1
  • 1
EJS
  • 1,011
  • 5
  • 14
  • 28
  • possible duplicate of [How to go to a specific element on page?](http://stackoverflow.com/questions/4801655/how-to-go-to-a-specific-element-on-page) – JeffC Sep 15 '15 at 15:25
  • Look at this answer, http://stackoverflow.com/a/14732703/2386774. It's JavaScript. – JeffC Sep 15 '15 at 15:25

1 Answers1

1

getLocation() function returns the location in the form of an object. Moreover, window.scrollBy() is a DOM javascript function, so you cannot probably use it in selenium without executing it. Also window.scrollBy() scrolls particular number of pixles in the DOM, instead use window.scrollTo() which scrolls to a particular location. Here's how you can do it -

driver.wait(function(){
driver.findElement(By.id('next_button'), function(ele){
    ele.getLocation().then(function(loc){
        driver.executeScript('return window.scrollTo('+loc.x+','+loc.y+');')
        .then(function(){
            ele.click();
        });
    });
});
},10000);

Hope this helps.

giri-sh
  • 6,934
  • 2
  • 25
  • 50
  • Thanks for the answer. I had to chain `findElement` and `getLocation` with a `.then` in order to get this to synchronize properly. Unfortunately the page didn't scroll with this, I get the same error on the `next_button` not being visible. Is the `browser` object in your example a normal chrome driver object? – EJS Sep 15 '15 at 12:50
  • Thanks for the update. I placed a sleep on the line before the click in your code, however I still cannot see any scrolling, and I still end up with the same error message at the click. – EJS Sep 15 '15 at 13:14
  • Can you console the `loc` variable and see if it is returning the object with any valid value? Also waiting for element to load would help i suppose, if its not in DOM already. Thanks – giri-sh Sep 15 '15 at 13:36
  • From the console I get that `loc.x = 429.5` and `loc.y = 1044.6875`. I tried to manually input anywhere between 0-3000 for x and y positions instead of using `getLocation`, however still nothing happens. Just to confirm that scrolling would indeed solve my problem, I tried to manually scroll during the 5 second wait right before `ele.click()` and indeed the rest of my code executed without errors. – EJS Sep 15 '15 at 13:57