Ensure that the page has completely loaded using WebdriverJS

Is there a reliable method to ensure that a page has fully loaded using selenium-webdriver in JavaScript? I came across this similar query, but I require an implementation specifically in JavaScript.

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;

var driver = new webdriver.Builder()
    .forBrowser('firefox')
    .build();

driver.get('http://www.google.com');

// Add code here to wait for the page to completely load...
// Possibly by using something like this...
// driver.wait(...);

// Then proceed with other tasks

driver.quit();

Answer №1

I discovered that this method perfectly fits my requirements.

browser.navigate('https://www.bing.com');

browser.waitFor(function() {
  return browser.executeScript('return document.readyState').then(function(pageState) {
    return pageState === 'loaded';
  });
});

// Perform actions after the webpage is fully loaded

Answer №2

This code snippet provides a solution for handling page loads after a user click, whether it opens in the same tab or a new browser tab.

  /* waitForPageLoad
   * This function compares the HTML IDs before and after the click to determine if the new page has loaded.
   * It waits until the page ID changes or times out.
   * @param {int} timeout
   * @param {string} link
   * @param {string} expectedTitle
   * @return {bool}
   */
  async waitForPageLoad(timeout, link, expectedTitle) {
    let oldHTMLId;
    let newHTMLId;
    let titleWaitingFor;
    const oldHtmlElement = await this.driver.wait(until.elementLocated(By.tagName('html')));
    await link.click();
    await this.driver.wait(async () => {
      const actualTitle = await this.driver.getTitle();
      titleWaitingFor = actualTitle;
      const newHtmlElement = await this.driver.wait(until.elementLocated(By.tagName('html')));
      const newHtmlElementId = await newHtmlElement.getId();
      const oldHtmlElementId = await oldHtmlElement.getId();
      oldHTMLId = oldHtmlElementId;
      newHTMLId = newHtmlElementId;
      return newHtmlElementId !== oldHtmlElementId
      && actualTitle.includes(expectedTitle);
    }, timeout);
    return oldHTMLId !== newHTMLId && titleWaitingFor.includes(expectedTitle);
  }


//Function for handling click opening in new browser tab

  /* getWindowHandlesAndExpectedPageInfo
   * Waits for the new window handle after a click and confirms the expected title.
   * Returns the title and URL of the new page.
   * @param expeted title
   * @return string Page Title and url { title: returnTitle, url: currentUrl }.
   */
  async getWindowHandlesAndExpectedPageInfo(expectedTitle, waitTimeout = 6000) {
    try {
      await this.waitForWindowHandleCount(2);
      let returnHandles;
      let returnTitle;
      await this.driver.wait(async () => {
        const handles = await this.driver.getAllWindowHandles();
        returnHandles = handles;
        await this.driver.switchTo().window(handles[1]);
        const actualTitle = await this.driver.getTitle();
        returnTitle = actualTitle;
        return actualTitle.includes(expectedTitle);
      }, waitTimeout);
      const currentUrl = await this.driver.getCurrentUrl();
      await this.driver.close();
      await this.driver.switchTo().window(returnHandles[0]);
      return { title: returnTitle, url: currentUrl };
    } catch (err) {
      console.log(`Function: getWindowHandlesAndExpectedPageInfo failed ${err}`);
      const handles = await this.driver.getAllWindowHandles();
      await this.driver.close();
      await this.driver.switchTo().window(handles[0]);
      return null;
    }
  }

  /* waitForWindowHandleCount
   * Waits for the expected number of window handles to be present.
   * @param int
   */
  async waitForWindowHandleCount(count, waitTimeout = 6000) {
    try {
      await this.driver.wait(async () => {
        const handles = await this.driver.getAllWindowHandles();
        return handles.length === count;
      }, waitTimeout);
    } catch (err) {
      console.log(`Function: waitForWindowHandleCount failed ${err} `);
    }
  }


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

Selenium does not support the input of text (email) characters

I'm currently working on creating a bot using Selenium to automate the input of email and password on Best Buy's website. Below is the snippet of code I have so far: browser.find_element_by_xpath("/input[@id='fld-e']").send_k ...

Applying CDNJS CSS or external CSS to Nodemailer HTML templates with Jade and Express: A Guide

I am attempting to send emails using node mailer. I have a jade template with HTML markup in an external file, which is compiled and rendered correctly. However, the styles inserted through maxcdn or cdnjs are not being applied. In this situation, how can ...

Make an ajax request to a method in YII framework

I need to send an AJAX call to a function within the directory structure outlined below: Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; Here is my view function: function uploadImage ...

Tips for enabling microphone/camera permissions in Microsoft Edge using Selenium

Is there a similar option like 'options.add_argument("--use-fake-ui-for-media-stream")' and 'options.add_argument("--use-fake-device-for-media-stream")' available for edgedriver? If so, what are those options? ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

Ways to create space around Navbar MUI for a more balanced design

Currently, I am working on designing a navigation bar using MUI. My goal is to create a navbar with some space on both sides similar to the one seen on If you take a look at Stackoverflow's navbar, you will notice that it also has space on either sid ...

Tips for exporting telegram information to a Google spreadsheet

Recently, I set up a basic telegram bot using the telegraf framework and wrote this code snippet to log essential data: bot.on('text', (ctx, next) => { console.log(`[text] ${ ctx.message.chat.id } ${ ctx.from.username } ${ ctx.message.chat.f ...

Resolving CORS issues: Troubleshooting communication between a React app and an Express server

After successfully running both the app and server locally, I encountered an issue upon deploying the express server. Whenever I try to make a request, I consistently receive the following error message: "has been blocked by CORS policy: Response to ...

Limiting jQuery searches to a specific region: Tips and tricks

If I have the code snippet below: <div class="foo"> <div> some text <div class="bar"> </div> </div> </div> <div class="foo"> <div> some text <div class="bar"> some text </div> </div> </ ...

Steps for triggering a re-render in a React component when an external value changes

I am currently working on a project that involves using Meteor and React. In my code, I have a class called WebRTC which handles all WebRTC-related logic: class WebRTC { this.isCalling = false; ... } In addition to the WebRTC class, there is ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

Creating subpages using IDs can be accomplished by following these simple steps

Currently, I am in the process of developing a website that contains a plethora of information, specifically news articles. Each news article on my site features an introduction and a header. Upon clicking on a particular news article, the full content is ...

Having difficulties accessing information from the HTML document

I face an issue with my code where I am unable to fetch the sectionID from tr. I want to retrieve the dynamic id of sectionID on each button click for deletion, but it always returns null. Below is the JQuery script: <script> $(function () { $(&apo ...

Issue encountered when trying to remove an event while a dialog is closed in a React useEffect

While working with my open dialog, I attempted to include a 'key-down' event. Unfortunately, the event continues to trigger even after the dialog is closed. To address this issue, I encapsulated the event handling function within the useEffect h ...

jQuery - delete a single word that is case-sensitive

Is there a way to eliminate a specific case-sensitive word from a fully loaded webpage? The word in question is "Posts" and it appears within a div called #pd_top_rated_holder that is generated by Javascript. The Javascript code is sourced externally, so ...

Ways to center vertically aligned buttons within cards in a React application with Material-UI

I've encountered an issue with my ReactJS project using material-ui. I created 3 cards, each with a paragraph of varying lengths. This caused the buttons to be misaligned vertically in each card, as the position differs due to paragraph size differenc ...

Utilizing Webdriver in C# to loop through elements and add their names to a screenshot array

My Plan: Grab the dropdown menu Find each option in the dropdown menu Click on each option, take a screenshot Progress so far: IWebElement DropDownMenu = driver.FindElement(By.XPath("//*[@id='DropDownMenu']/span")); ...

What is the best way to connect an HTML file to a controller in Angular.js?

When developing an app module using the MEAN stack with MVC, I created a folder named AppModules. Inside AppModules, there is a folder called search, which contains three subfolders: models, views, and controllers. I've written an HTML file in the vie ...

Issue with event.stopPropagation() in Angular 6 directive when using a template-driven form that already takes event.data

I am currently developing a citizenNumber component for use in forms. This component implements ControlValueAccessor to work with ngModel. export class CitizenNumberComponent implements ControlValueAccessor { private _value: string; @Input() place ...

Is it possible to store multiple types of locators (xpath, css, id, name) for the same web element variable within a single Page Object Model (POM

Is it possible to store multiple types of locators (xpath, css, id, name) for the same web element variable in a single POM page? I understand that we cannot have different locators with the same logical name within a POM class file, but can we reference ...