Using Selenium to wait for a JavaScript script to return a value that matches the desired value

My current challenge in JavaScript involves waiting for a specific string or boolean value to be matched.

Here is the relevant JavaScript code snippet:

document.getElementById('video_html5').seeking;

When this code is executed, it returns either "false" or "true". I need to wait until the value is "false", indicating that the video is not seeking. However, I have only been able to figure out how to wait for a general JavaScript command value without being able to test for specific text matches.

new WebDriverWait(driver, 30)
    .until(ExpectedConditions.jsReturnsValue("return document.getElementById('video_html5').seeking;"));

There are cases where the returned value is a string rather than a boolean, so I must also account for comparing strings.

I managed to achieve this functionality in Ruby, but I am still looking for a way to do it in Java:

wait_element = @wait.until { @driver.execute_script("return document.getElementById('vid1_html5_api_Shaka_api').seeking;").eql? false }

Answer №1

If you want to create your own unique expected conditions, you can do so by writing custom code.

public class CustomConditions {

  public static ExpectedCondition<Boolean> myCustomCondition() {
    return new ExpectedCondition<Boolean>() {
      @Override
      public Boolean apply(WebDriver driver) {
        return (Boolean) ((JavascriptExecutor) driver)
          .executeScript("return document.getElementById('video_html5').seeking === 'string_value' || ... ");
      }
    };
  }
}

You can then use this custom condition in your tests like this:

WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(CustomConditions.myCustomCondition());

Answer №2

Here is a simple method to execute JavaScript code using WebDriver and wait for the output:

public Object executeScriptAndWaitOutput(WebDriver driver, long timeout, final String command) {
  WebDriverWait wait = new WebDriverWait(driver, timeout);
  wait.withMessage("Timeout executing script: " + command);

  final Object[] out = new Object[1];
  wait.until(new ExpectedCondition<Boolean>() {
    @Override
    public Boolean apply(WebDriver d) {
      try {
        out[0] = executeScript(command);
      } catch (WebDriverException we) {
        log.warn("Exception executing script", we);
        out[0] = null;
      }
      return out[0] != null;
    }
  });
  return out[0];
}

Answer №3

After gathering insights from various sources, I was able to solve the issue by implementing the following method:

public Boolean checkStateSeeking() throws InterruptedException {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        Boolean seekingState = (Boolean) js
                .executeScript("return document.getElementById('vid1_html5').seeking;");

        while (seekingState) {
            // System.out.println(seekingState);
            seekingState = (Boolean) js
                    .executeScript("return document.getElementById('vid1_html5').seeking;");
        }

        return seekingState;
    }

Answer №4

Creating a function to monitor element changes and wait for a specified amount of time before moving on, based on the element's xpath and expected value.

 public static String waitForElementChange(WebDriver driver, String expectedValue, String path, int waitTime) throws InterruptedException {
    JavascriptExecutor js = (JavascriptExecutor) driver;
    String elementValue = (String) js
            .executeScript("return document.evaluate(\""+path+"\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value;");

    while (!(elementValue.equals(expectedValue)) && (waitTime > 0)) {
        Thread.sleep(1000);
        waitTime--;
        elementValue = (String) js
                .executeScript("return document.evaluate(\""+path+"\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value;");
    }
    return elementValue;
}

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

What is the best way to identify different directives within the same $scope?

When it comes to calling directive functions from controllers, I follow this approach: function myControllerFunction = function () { $scope.highlight(); } The highlight() function is defined within the directive itself. But what if there are two dif ...

Encountered an Error in Express.js: Unable to POST /users

I am currently in the process of learning the MEAN stack by following a tutorial and have encountered an error. Unfortunately, I am having difficulty identifying exactly where I went wrong. While attempting to test routes in Postman by creating a user, I ...

"Utilize parameter passing with mapGetters in the Vuex state management system

Hello there! I'm currently working on a Vue.js project and using modules. I am trying to get filtered data from a getter, but I'm unsure how to provide parameters. Specifically, I need to pass a 'name' parameter to the Getter. How can ...

Using a variable value as a regular expression pattern: A beginner's guide

I'm at my wit's end - I can't figure out where I'm going wrong. I've been attempting to replace all instances of '8969' but I keep getting the original string (regardless of whether tmp is a string or an integer). Perhaps ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Unveiling the true purpose of the 'Build project' feature in IDEA

Upon creating a new project in Idea, when the "build project" button is clicked, Gradle initiates two tasks Executing tasks ':classes :testClasses'... I looked for a specific task or script related to "build project," but couldn't find one ...

Refresh your webpage with new content and modified URLs without the need to reload using window.history.pushState

Hey everyone, I'm looking to incorporate window.history.pushState into my website, but I'm unsure of how to go about it... What I'm aiming for is to have a page dashboard.php and update the URL to dashboard.php?do=edit&who=me, while loa ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

Accessing the value of a hidden field within an ng-repeat loop when binding to an HTML table

I am working on a project where I have an HTML table with data being bound from AngularJS. The structure looks something like this: <tr ng-repeat="item in List| filter: { MachineType: 'Physical' }"> <td>{{item.MachineType}}< ...

Difficulty with Java Content Assist in Eclipse

Having an issue with the content assist feature in Java-Eclipse on Windows 10. As I type my code, the pop-up window suddenly appears and moves to the top-left corner of my screen. I have to hit ESC to return to the main editor before continuing with my c ...

How can Java application benefit from incorporating plugins?

Is there a simple way to incorporate plugins into a Java application that can be easily activated when needed and comes with thorough documentation? I am seeking something akin to OSGI, JPF, and JSPF. However, OSGI is too complex, JPF lacks documentation, ...

Creating a regular expression to match special characters using JavaScript

I'm making an attempt to verify certain characters in my code. If the input field contains specific characters for each character, it will return true; otherwise, it will return false. function isChar(value) { //Creating a regex pattern to permit ...

JavaScript - Global Variable

Is it possible to declare and assign a value to a global variable in one JavaScript file and then reference it in another JavaScript file multiple times? Can Angular.js be utilized in a Velocity macro file, aside from HTML files? ...

Utilizing DeployR Server and the Javascript API yields a message of 'Project in Use' for large data returns

Let me start by saying that I primarily work with JavaScript, but recently I've delved into a project involving R/DeployR, so my expertise in this area is still limited to what I've learned in the past few months. In this project, I am using the ...

Converting HTML widget code to NEXTjs code for integration in an application (CoinMarketCap Price Marquee Ticker)

Having trouble integrating the CoinMarketCap Price Marquee Ticker Widget into my NEXTjs app. I'm outlining my process and hoping for some suggestions from others who may have attempted this. Template Code: To embed the widget in an HTML page, here is ...

Javascript - Spin the Wheel of Fortune

I am looking to create a wheel of fortune using JavaScript. My goal is to set both the output and starting position of the wheel. When the user spins the wheel at a minimum speed, it should rotate multiple times based on the speed before landing on the des ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

Altering the context of Javascript script execution

I needed to switch the JavaScript execution context from the parent window to the child window. I was able to successfully load my script objects and functions into the child window context, however, I encountered difficulty in making third party libraries ...

EmeraldSocks Tweenmax motion design

I need help with Tweenmax animation. I'm attempting to animate an id selector, but nothing is happening. Both the selector and content are unresponsive. Can someone assist me? Here is the code: <!DOCTYPE html> <html> <head> ...

Upgrade scenes in ThreeJS by implementing cross fading between scenes from version 101 to 107

Discovering a helpful example by Fernando Serrano on how to smoothly transition between 2 scenes in ThreeJS was quite enlightening. I also stumbled upon this modified JSFiddle version using ThreeJS 101, which works well but faced an issue... Following the ...