A guide on using JavaScript with Selenium to continuously refresh a page until a specific element disappears

When working with selenium in JavaScript, I have a challenge where I need to constantly refresh the page until a specific element disappears. The issue arises because selenium uses promises, and using a for loop creates multiple promises even when the condition is met, causing them to be resolved later on. Additionally, I am required to include driver.sleep(5000) for some reason.

$browser.get("https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html").
then( function()
{
var p=Promise.resolve();
for (let index = 0; index < 5; index++) {    
    p = p.then(() => 
    isElementDisplayedAfterrefresh($driver.By.xpath("//span[text()='PouchDB']"), "input"))
    .then(a=>$browser.sleep(3000))
    .then(()=>$browser.navigate().refresh())
}
return p;
}
).then(
    ()=>console.log('done'))

The code should stop if the element is not displayed, and continue refreshing if the element is still visible. How can I iterate through promises sequentially without knowing the results or number of iterations? I need to return a Promise type and also know how to break out of the loop. Thank you!

Edit

https://gist.github.com/saiparth/045c32267e55b836f139bdac6597e57b The issue I'm facing is that it schedules commands for all 5 iterations, regardless of whether the previous index worked or not. Additionally, I am unable to use async/await in this scenario.

Answer №1

Is there a way to determine if the element is currently visible without having to constantly refresh the page?

.then(a=>$browser.sleep(3000))
maybe it should be more like

.then((a => { if(a.isDisplayed() == true) { console.log('element is displayed, no need for action') } 
  else { 
     $browser.sleep(3000))
    .then(()=>$browser.navigate().refresh())
}  }))

Answer №2

At last, the solution presented itself to me after consulting this source

function executeTask(id) {
    if (id >= 10) {
        return;
    }
   return $browser.findElements(By.xpath("//span[text()='PouchDB']")).then(elements => elements.length==0)
        .then(function (isFound) 
        {
            if (!isFound) {
               return $browser.sleep(5000)
                .then(() => $browser.navigate().refresh())
                .then(elements=>executeTask(id + 1))
            }  
            else{
               return;
            }
        });
}
$browser.manage().window().maximize();
$browser.get("https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html")
.then(elements=>executeTask(5))
.then(elements=>console.log('task completed'))

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

Immersive Visual Symphony through Dynamic Multi-Layered

My goal is to create captivating animations for my multiple background images. Here's the CSS code I've come up with: .header { background-image: url('/img/cloud2.png'), url('/img/cloud3.png'), url('/img/cloud1.png&apos ...

The Firebase Auth Multifactor feature does not include the multiFactor property in the user object

Looking to implement Multi-Factor Authentication (MFA) in my web app, but encountering an issue where the multiFactor property is missing in the code snippet below: import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.2/firebase-app.j ...

Thymeleaf: Expression parsing error

I am working on a Thymeleaf template that includes pagination functionality. <ul class="results_perpage" > <li th:if="${previous != null}"><a th:href="javascript:movePage(`${previous}`);" class="results_menu" th:text="PREVIOUS">< ...

Set the variable after catching it

Within my AngularJS application, I am utilizing a $watchCollection function to call the getBalance(address) function within the listener. $scope.$watchCollection('settings', function() { for (i = 0; i < $scope.settings['accounts&ap ...

Is there a way to achieve a transparent background while animating the second text?

I am seeking to create a unique typography animation that involves animating the second text, which is colored and consists of multiple text elements to animate. The animation should showcase each text element appearing and disappearing one after the other ...

When using Selenium WebDriver to locate an object, an error may occur stating that the result of the xpath expression is "[object Text]" instead of an element as expected

I am currently utilizing Selenium to validate the existence of specific text within a web page. Here is an example of how the HTML appears. <html> <div class="a-content"> <!--!-->==$0 " Text to Locate" <b ...

The issue of "window is not defined" persists when using P5.js with Next.js, even

How can I import a component with a logo created using p5.js when encountering the error: window is not defined I researched solutions and discovered that within useEffect, the component will only mount once the window object becomes accessible. To test ...

What are the steps for adding Firefox to the system PATH on a Linux instance hosted on Amazon Web Services?

I have a question regarding adding Firefox to the system PATH on an Amazon Web Service Linux instance. I recently installed firefox to /home/firefox instead of /usr/bin. Can anyone provide guidance on how to do this? Thank you! After importing selenium, ...

WebpackError: The global object "document" could not be found

I am encountering an issue with my website build using gatsby.js and bulma. While building the site, I receive the following error message: WebpackError: document is not defined The only instance where I use document is for the navbar-burger toggle code ...

Excess space at the bottom of the Heatmap chart in Highcharts

I am facing an issue with a heatmap having extra space at the bottom that I cannot seem to remove. Despite trying various solutions from different Stack Overflow threads, such as adjusting chart.marginBottom, chart.spacingBottom, x and yAxis margins, and d ...

What is the best approach for developing an npm package containing multiple Vue directives? Should each directive have its own separate package, or should they

While I have successfully created an npm package by exporting a single vue directive in the src/index.js file, I am now faced with the challenge of creating a package that allows for the use of multiple vue directives. Unfortunately, I have been unable t ...

Retrieve the selected checkboxes from the latest .change() trigger

I'm facing an issue with a basic question that I can't seem to find the right terms to research for help. The problem revolves around a .change() listener that monitors checkbox changes within a div (used to toggle Leaflet Map layers). My goal i ...

Retrieve nodes that are children of another node

Here is the code snippet that I am working with: <div id="page1-div" style="position:relative;width:1347px;height:1189px;"> <img width="1347" height="1189" src="target001.png" alt="bac ...

Is the Android Webview causing input boxes to double up?

Looking to develop an Android application that utilizes a webview for users to input their username/password, but encountering a strange issue where tapping on the input boxes creates duplicates (as shown in the image below). I have implemented the iScroll ...

AXIOS: Is it possible to send multiple data items in a single POST request to an API?

My form collects data, which is then sent to an API using the new FormData(). However, one of the items in the model contains multiple attributes in the MongoDB model. Since the form requires a 1-to-1 key-pair relationship, it can't be sent as an obje ...

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...

JavaScript: Trouble with statement execution

My code is designed to classify a point as 1 if it's above the line y=x, and -1 if it's below the line y=x. I visually represent this line in a canvas by plotting y=x (although due to invertion on the y-axis, it appears like y=-x). For each point ...

Tips for efficiently organizing and maintaining a selection of JavaScript variables by easily adding and removing them as needed

I am currently developing items that will be shown on a webpage. I achieve this by utilizing the following code: var popup = "something..." Is there a method to keep track of all the created popup variables and control them efficiently using: adding a ...

Should I consolidate my ajax requests into groups, or should I send each request individually?

Currently working on an ajax project and feeling a bit confused. I have 3 functions that send data to the server, each with its own specific job. Wondering if it's more efficient to group all the ajax requests from these functions into one big reques ...

Display a custom AngularJS directive on content loaded through $http request

I'm facing a dilemma. I have created a directive app.directive('a', function() { return { restrict: 'E', link: function(scope, elem, attrs) { elem.on('click', function(e){ ...