Protractor: Moving further down the page

One issue I encountered is with a button on my page that becomes visible only when the user scrolls down. As a result, Protractor tests are throwing an error:

UnknownError: unknown error: Element is not clickable at point (94, 188).

I attempted to resolve this by using the following code snippet:

browser.executeScript('window.scrollTo(0,document.body.scrollHeight)');

This solution worked in Protractor's elementexplorer.js, but unfortunately, it doesn't have any impact in my regular tests. Is there another workaround for this problem?

Answer №1

Patience is key when waiting for a promise to be fulfilled. The example below is taken from an open issue

browser.executeScript('window.scrollTo(0,0);').then(function () {
    page.saveButton.click();
})

Update: Although this question dates back to May of 2014, it continues to attract visitors. To clarify: window.scrollTo(0, 0) will scroll to the top left corner of the current page.

If you wish to scroll to the bottom of the page, you can use

window.scrollTo(0, document.body.scrollHeight)

as suggested by @jsuser in this answer

A more contemporary approach involves

browser.actions().mouseMove(element).perform();

Credit goes to @MartinBlaustein in this answer

Answer №2

Discovering a simpler solution, I stumbled upon a neat trick. To smoothly scroll to a specific element on the page, simply execute this line of code:

    browser.actions().mouseMove(element).perform();

Once executed, watch as the browser elegantly shifts its focus onto the desired element.

Answer №3

In addition to the previous response, I would like to offer further clarification.

The following piece of code, within the 'executeScript' function call:

'window.scrollTo(0,0);'
  • Scrolls the window upwards to the coordinates 0,0, effectively bringing it to the very top
  • If you have a specific location in mind, simply adjust the coordinates accordingly.

If your intention is to reach the bottom of the window, as was my objective, you can input a large number in the 'y' coordinate, as demonstrated here:

browser.executeScript('window.scrollTo(0,10000);').then(function () {
    expect(<some control>.<some state>).toBe(<some outcome>);
})

Answer №4

If you're facing the same issue I was encountering:

I needed to scroll to the bottom of the page to load more data in an infinite scroll setup. I experimented with different variations of window.scrollTo and arguments[0].click() but couldn't get it to work.

Eventually, I discovered that in order to make the page scroll, I first had to click on any element within the window to bring focus to it. After doing so, window.scrollTo(0, document.body.scrollHeight) worked perfectly!

Here's an example code snippet:

element(by.className('<any element on page>')).click();
browser.executeScript('window.scrollTo(0,document.body.scrollHeight)').then(function(){
// add your verification logic here
});

Answer №5

In my experience, I've discovered that utilizing a util helper and integrating it into page objects or test files can be quite beneficial. Here's an example of how I implemented this approach:

utils.js

module.exports = {
  scrollIntoView: function(el) {
    browser.executeScript(function(el) {
      el.scrollIntoView();
    }, el.getWebElement());
  }
}

within a page object...

var scrollIntoView = require('../utils').scrollIntoView;

module.exports = {
  clickBackBtn: function() {
    var el = element(by.buttonText('Go back'));
    scrollIntoView(el);
    el.click();
    return;
  }
}

in the actual test script...

it('should allow the user to navigate back to the profile page', function() {
  PageObject.clickBackBtn();
  expect(browser.getCurrentUrl()).toContain('/user/profile');
});

Answer №6

If you're seeking a quick way to navigate to the top or bottom of a lengthy page, try using the 'HOME' key to return to the top or the 'END' key to reach the bottom.

For example:

browser.actions().sendKeys(protractor.Key.HOME).perform();

or

browser.actions().sendKeys(protractor.Key.END).perform();

Answer №7

The question was originally marked as correct, but after updating to the latest version of Chrome (v54), the code below may provide the best solution:

browser.actions().mouseMove(element).perform();

Answer №8

If you're looking for an alternative method, give this a shot:

this.customScrollPage = function (element) {

    function scrollExecution() {
        return browser.executeScript('arguments[0].scrollIntoView()',
            element.getWebElement())
    }

    browser.wait(scrollExecution, 5000);

};

Answer №9

If you want to easily navigate to a specific element on a page, simply scroll down until you find it and then click on it. The following code has been tested and verified to work with the latest version of Protractor:

it('navigate to element', function() {
           browser.driver.get('https://www.seleniumeasy.com/');
            var btnSubscribe= element(by.id('mc-embedded-subscribe'));
            browser.executeScript("arguments[0].scrollIntoView();", btnSubscribe);
             browser.sleep(7500);
             btnSubscribe.click();
          });

Answer №10

implement

let centerElement = async (browser, element) => {
    await browser.executeScript(`arguments[0].scrollIntoView({block: "center"});`, element.getWebElement());
};

Use this function to scroll the element into the center of the window.

Answer №11

After trying out all the techniques mentioned above, I can confidently say that three things are guaranteed to work:

// To scroll to the top of the browser page
browser.actions().sendKeys(protractor.Key.HOME).perform();

// To scroll to the bottom of the browser page
browser.actions().sendKeys(protractor.Key.END).perform();

If the scrolling functionality is specific to a certain area within the browser, click on that area first before using the code provided above.

// For alternative scrolling methods, you can visit: "https://www.guru99.com/scroll-up-down-selenium-webdriver.html"
// The most effective approach is to use the following snippet where Element refers to the XPath 
let Element = element(by.xpath(optionid));
await browser.executeScript("arguments[0].scrollIntoView();", Element.getWebElement());

Answer №12

I faced a similar problem, but I managed to find solutions using two different approaches.

//#region Focus
var checkElem = await element(by.xpath("SomeXpath"));
await browser.executeScript("arguments[0].focus()", checkElem);

If the above code doesn't work, try this alternative:

//#region Adjust_To_Center
var focusAdjustment = await element(by.xpath("SomeXpath"));
await browser.executeScript('arguments[0].scrollIntoView({block: "center"});', focusAdjustment);

Answer №13

If you're finding it difficult to reach the bottom of the page due to a blocking footer, you can easily scroll down using this simple code snippet:

await browser.controlFlow().execute(function () {
  browser.driver.actions().sendKeys(protractor.Key.END).perform();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conceal all columns apart from the first when expanding/collapsing a table using

I have a table with a single header and multiple columns, and I am trying to implement an expand/collapse feature based on header clicks using the code snippet below: $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100 ...

What is the best way to insert fresh input values into a different element?

click here to view image description I am working with an input element where I take input values and store them in an element. However, I would like to know how to input new values into the next element. Any assistance would be greatly appreciated. Thank ...

Create div elements using JSX and add them to an array

I am working with a structure that looks like this: var circle = { 'one': {items: []}, 'two': {items: []}, 'three': {items: []}, 'four': {items: []} }; Each items array needs to contain 10 unique ...

Divide the division inside the box by clicking on it

I am looking to create a unique div with a random background color and a width of 100px. Additionally, I want to have a button that, when clicked, will split the original div into two equal parts, each with its own random background color. With each subs ...

Is it possible to replicate a stale closure similar to React's useEffect hook without the use of the useEffect hook?

I have a good understanding of closures, but I am struggling to grasp how a stale closure can be created in React's useEffect without providing an exhaustive dependencies array. In order to explore this concept further, I am attempting to replicate a ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

The <b-list-group-item> component in a Vue.js CLI application using bootstrap-vue is failing to render

My Vue-CLI app uses Bootstrap-vue and axios to fetch JSON data. The HTML code in my App.vue displays the data using UL and LI tags: <p v-if="loading">Loading...</p> <ul v-else> <li v-for="(value, key) in post" :key="key"> ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

Accessing API using Next.js 14

I am facing an issue with the following code which is written in next.js. The error displayed on the console is: GET http://localhost:3000/products/porducts.json 404 (not found) Additionally, I'm encountering this error: Uncaught (in promise) SyntaxE ...

Console log messages not displaying in Express.js app method

const express = require("express"); const app = express(); app.listen(3000, function () { console.log("Server started at port 3000."); }); app.get("/", function (req, res) { console.log("Hello, world"); const truck = "drive"; res.send("Hello, ...

Issue with Redux saga not responding to action initiated by clicking on an icon

Declaration of Saga function* DoStuffInSaga({myRef}){ try { console.info("saga running"); return yield delay(1000, 1); } catch(error){ console.warn(error); } } export function* mySaga(){ yield all([ yi ...

Transfer or duplicate an SVG image from the bottom div to the top div

Is there a way to move a div from the chart_div to the movehere div? I've tried duplicating it below the current svg, but I'm having trouble targeting just the header row ('g' element) specifically. Here is the HTML: <script type= ...

How can I show tab objects in a Chrome extension?

I'm currently working on developing a new Google Chrome extension that focuses on tab organization. Despite the abundance of similar extensions already available, I am determined to create my own unique solution. One idea I have is to create a popup w ...

I am running several classes in selenium, but I am facing an issue with locating the driver in one of the classes

Download testng.xml file Check out the base driver class Encountering a null pointer error in a different class method ...

Steps to validate individual input text fields that create a date and display an error message if the date is not valid

Currently, I am working on a React Material UI component designed to capture a user's 'Date of Birth'. This component consists of three separate inputs for the day, month, and year. In order to enhance this functionality, I would like to im ...

Python script depends on the geckodriver from Selenium, which must be present

Encountered error: Traceback (most recent call last): File "/home/ubuntu/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib/python3.6/subprocess.py", line 729, in __init__ rest ...

Showing the precise age in years by utilizing the provided 'Date of Birth' selected from the datePicker

Is it possible to retrieve the date entered in the datePicker and use it to populate the current age field in a PHP file using either PHP or Javascript? if ($key == 'currentage') { $group[] = $this->form->createEleme ...

Automated browser testing (using C#) - continuously refreshing the page until a specific element's style disappears

I'm having difficulty with a specific method I need assistance with. Here is the task at hand: First, I want to load a webpage Once the page is loaded, I need to wait until a particular element on the page has the style attribute "hidden: true;". Th ...

Is it possible to uncheck a checkbox from a list, even if some of them are already unchecked?

I am attempting to implement a feature where checking a checkbox selects all others in the list, and unchecking one deselects all. Currently, only selecting one checkbox allows me to check all the rest, but unchecking one doesn't trigger the reverse a ...

How to Process a Stripe Payment using jQuery AJAX (JavaScript Only)

I'm in the process of creating a custom payment form for Stripe and I want to manually initiate the AJAX call to connect with Stripe. Instead of relying on a typical submit event. Unfortunately, it seems like I might be sending the request to the inc ...