All files / webdriverio/src/commands/browser switchWindow.js

100% Statements 12/12
100% Branches 8/8
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                                                                  6x 1x     5x   5x 11x         11x 11x 3x           8x 8x 1x       1x    
 
/**
 *
 * Switch focus to a particular tab / window.
 *
 * <example>
    :switchWindow.js
    it('should switch to another window', () => {
        // open url
        browser.url('https://google.com')
        // create new window
        browser.newWindow('https://webdriver.io')
 
        // switch back via url match
        browser.switchWindow('google.com')
 
        // switch back via title match
        browser.switchWindow('Next-gen WebDriver test framework')
    });
 * </example>
 *
 * @param {String|RegExp}  urlOrTitleToMatch  String or regular expression that matches the title or url of the page
 *
 * @uses protocol/getWindowHandles, protocol/switchToWindow, protocol/getUrl, protocol/getTitle
 * @alias browser.switchTab
 * @type window
 *
 */
 
export default async function switchWindow (urlOrTitleToMatch) {
    /*!
     * parameter check
     */
    if (typeof urlOrTitleToMatch !== 'string' && !(urlOrTitleToMatch instanceof RegExp)) {
        throw new Error('Unsupported parameter for switchWindow, required is "string" or an RegExp')
    }
 
    const tabs = await this.getWindowHandles()
 
    for (const tab of tabs) {
        await this.switchToWindow(tab)
 
        /**
         * check if url matches
         */
        const url = await this.getUrl()
        if (url.match(urlOrTitleToMatch)) {
            return tab
        }
 
        /**
         * check title
         */
        const title = await this.getTitle()
        if (title.match(urlOrTitleToMatch)) {
            return tab
        }
    }
 
    throw new Error(`No window found with title or url matching "${urlOrTitleToMatch}"`)
}