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} `);
}
}