Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close the current tab of the browser in protractor with out closing the complete browser

Tags:

protractor

In the application i have two options "Google , Twitter" . When i click on any option it will open in new tab.

In my test case , i would like to click on google or twitter option and close the google or twitter tab and return back to the my application.

Is there any way to close only newly opened tab.

I tried below solutions.

browser.close(); is closing the entire browser.

Can any one help me how to close only tab of the browser ( in my case google tab or twitter tab) with out closing the entire browser in protractor

like image 985
vasundhara Avatar asked Feb 02 '18 07:02

vasundhara


People also ask

How do you close a browser tab in Protractor?

window(handles[1]); browser. driver. close();

How do I close the current tab in selenium?

While doing stuff with selenium multiple browsers with multiple tabs will normally opens in order to close these tabs close() and quit() methods are used. close() method is used to close the current browser window on which the focus is set, on the other hand quit() method essentially calls the driver.

How do you handle a tab with a Protractor?

Handle simple Two Browser Windows / TabsClick on the Open New Window button, application open new window with google page. Make the protractor to sleep for 5 seconds; otherwise, it may not find the newly opened tab. 6. Switch to the window using switchTo().

How do you close the child window on a Protractor?

switchTo(). window(windowHandler); await browser. close(); } } await browser.


2 Answers

You can try the following:

Switch to the new opened tab. Close the current windows (in this case, the new tab). Switch back to the first window.

browser.getAllWindowHandles().then((handles) => {
    browser.driver.switchTo().window(handles[1]);
    browser.driver.close();
    browser.driver.switchTo().window(handles[0]);
});
like image 50
Oleksii Avatar answered Oct 01 '22 17:10

Oleksii


This is how I used it in one project.

    const allWindowHandlers = await browser.getAllWindowHandles();

        if (allWindowHandlers.length > 1) {
          for (let windowHandlerIndex = 1; windowHandlerIndex < allWindowHandlers.length; windowHandlerIndex++) {
            const windowHandler = allWindowHandlers[windowHandlerIndex];
            await browser.switchTo().window(windowHandler);
            await browser.close();
          }
        }

    await browser.switchTo().window(allWindowHandlers[0]);

You can use it inside your steps implementation.

You can use it before starting a new scenario, to be sure that only the first window is selected and everything else is closed.

like image 20
iidov Avatar answered Oct 01 '22 18:10

iidov