Checking if a webpage is a login page using WebdriverIO

Currently, I am utilizing Javascript and webdriverio (v2.1.2) for the purpose of data extraction from an internal site that is SSO enabled. If authentication has already been done on another application, there is no need to log in again for this specific application, which is a common scenario in enterprise intranet applications. Here is my plan:

  • Create a client with the necessary capabilities
  • Provide the required URL
  • Just for fun: Print out the title of the page
  • Determine if a certain element exists on the page. If it does, then it is a login page. If not, then it is not a login page.

    login = function (username, password) {
    if (!browserClientUtil) {
        throw "Unable to load browserClientUtil.js";
    }
    browserClientUtil
      .createClient()
      .url(_Url)
      .title(function (err, res) {
            console.log('Title is: ' + res.value);
      }) .isExisting('input#login_button.login_button', function (err, isExisting) {
        browserClientUtil.getCurrentClient()
            .setValue('input#USER.input', username)
          .setValue('input#PASSWORD.input', password)
          //.saveScreenshot('ultimatixLoginDetails.png')
          .click('input#login_button.login_button')
          .pause(100);
          handlePostLogin();
    });
    

    };

Is this approach the most optimal one? I attempted to separate the code for verifying the login page into a distinct function, but it did not yield the desired results as everything in webdriver functions asynchronously through callbacks and I am uncertain if I am implementing it correctly. How can I efficiently return a value from a callback function that will ultimately be the final output of that specific function?

    login = function (username, password) {
    if (!browserClientUtil) {
        throw "Unable to load browserClientUtil.js";
    }
    browserClientUtil
      .createClient()
      .url(_Url)
      .title(function (err, res) {
            console.log('Title is: ' + res.value);
      });
      if(isThisLoginPage()){
            browserClientUtil.getCurrentClient()
            .setValue('input#USER.input', username)
          .setValue('input#PASSWORD.input', password)
          //.saveScreenshot('ultimatixLoginDetails.png')
          .click('input#login_button.login_button')
          .pause(100);
          handlePostLogin();
        }
};

    isThisLoginPage = function() {
    var client = browserClientUtil.getCurrentClient();
    if(!client) {
        throw "Unable to get reference for current client, hence cannot validate if this is login page.";
    }

    client.isExisting('input#login_button.login_button', function (err, isExisting) {
        if(isExisting) {
            return true;
        }
    });
    return false;
};

Answer №1

If you want to streamline your workflow, consider creating custom commands that encapsulate other actions. For instance, you could define a command for logging in:

browserClientUtil.addCommand("login", function(url, user, pw, cb) {
    this.url(url)
        .setValue('#username', user)
        .setValue('#password', pw)
        .submitForm('#loginForm')
        .call(cb);
});

This approach simplifies the execution of complex asynchronous WebDriver tasks with a single function call. It paves the way for building a robust toolchain. As a result, your test script would resemble something like this:

browserClientUtil
    .login("http://example.com/login", "jane.smith", "P@ssw0rd")
    .getTitle(function(err, title) {
        console.log(title);
    })
    // ...

Cheers!

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

Having spaces between elements is necessary due to the insertion of a new line and the use

I am working on an HTML page where I have the following code snippet: <div id="div"></div> My task is to dynamically add two elements within this div using JavaScript. The issue arises when adding a and button elements. a1 = document.createEl ...

Incorporating Paged.JS functionality into a React/JS web application

My attempt to showcase my html page using paged.js in a react project has hit a snag. The html loads perfectly when accessed from local host (not via npm start, but the live server extension on vscode). However, following the steps outlined on this website ...

Modify each combination of characters surrounded by two symbols within a string

How can I replace the string between two symbols in my Angular code? For example, how can I change "Hello "I am" software coordinator as "freelancer"" to "Hello {I am} software coordinator as {freelancer}" I have been trying to write the code for this, ...

Forming a JSON structure using input variables

Currently, I am attempting to construct a JSON object using variables extracted from a form. var firstName = $('#firstName').val(); var lastName = $('#lastName').val(); var phone = $('#phoneNumber').val(); var address ...

Guide on resolving the issue with CORS policy

I am currently working on a project that involves using socket.io. However, I have encountered an error in the browser console: Access to XMLHttpRequest at 'https://back.escootrent.com/socket.io/?EIO=4&transport=polling&t=OwxDnkM' from ...

Limit the outcomes of the Ionic timepicker

Currently, I am utilizing the ionic datetime feature. However, instead of receiving just the hours, minutes, and seconds, the result I am getting looks like this 2020-10-05T00:00:27.634+07:00. What I actually require from this output is only 00:00:27. Is ...

Choose options with selectize.js including option separators

My list of countries includes options with dashes as separators, but when I use selectize they disappear. How can I visually separate items in the list without using labelled option groups? <select class="form-control" id="Country" name="Country"> ...

Having trouble selecting radio buttons in Internet Explorer with Selenium WebDriver

I am facing an issue where I cannot select the radio button using Selenium web driver. Here is the HTML code: <input name="PersonalDetails.Paperless" class="input-validation-error" id="Paperless" type="radio" data-val-required="Contract notes selectio ...

Using MongoDB Object as middleware in Express applications

I’m facing issues trying to access the "DB" database object that gets created when the MongoDB client module establishes a connection with my MongoDB database. Currently, I am encountering an error indicating that in data.js, 'db' is not defin ...

Is there a way to undo the click event in Javascript?

Is there a way to revert back to the initial position after clicking? I successfully changed the x icon to a + icon on click, but now I'm struggling to reverse that action. I've tried using MOUSEUP and DBLCLICK events, but they aren't ideal ...

Team members

Just started diving into Angular and practicing coding with it while following video tutorials. However, I've stumbled upon something in my code that has left me puzzled. I'm curious about the significance of the line "employees: Employee[]" in ...

"Troubleshooting ways to resolve babel-eslint import/export issues without the need for a configuration

Upon running npm start, I encountered the following error message: Parsing error: 'import' and 'export' may only appear at the top level After investigating this issue, suggestions included updating the eslint configuration file with ...

Combining THREE.Sprite with fog or utilizing THREE.ParticleSystem with an array of texture maps

Currently attempting to create a particle system using Sprite, however, encountering an issue where Sprite does not appear to respond to the "fog" parameter, meaning it does not fade away with distance. While ParticleSystem does adhere to the fog parameter ...

What is the best way to extract the geometry information from a gltf object?

I've been using three.js to load a gltf file with the gltfloader, and now I'm trying to create a particle system. However, I'm having trouble getting the geometry object that I need. function initModel() { var planeGeometry = new THREE ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Combining Selenium with Python to interact with multiple website formats in a single script

When interacting with the website, I encountered two different formats: http://15256160037.58food.com/contact/ http://hubeianran.58food.com/contact/ There are also two variations in link format, with titles specified as a[1] or a[2]: <div class=" ...

The NodeJS environment is experiencing issues with async JavaScript functions returning undefined

I'm struggling to call a function that fetches data from an API, compares it with input, and should return either 0 or 1 for use in my code. However, the function is currently returning undefined. I can't seem to wrap my head around it. async fu ...

restore the HTML element to its initial position after being moved

I am utilizing document.getElementById('Droping1').style['-webkit-transform'] = translate(0px,'+Ground+'px)'; in order to relocate an HTML element. How can I return it to its original position for reusability without t ...

focusing on a single div amidst a sea of interwoven dynamically generated divs

I am currently working with the liferay framework and I am facing a challenge where I need to apply inline JavaScript to target a very specific div on my webpage. The catch is that this div is nested within multiple dynamically added divs with varying clas ...

Using Next.js for dynamic routing with JSON arrays in getStaticPaths

I am currently facing an issue while trying to incorporate a json file with multiple arrays into my Next.js application. The structure of the json file is quite complex, and I'm unsure about how to convert it into a format that can be effectively util ...