Skip to content

fix(webdriverio): better handle window switching in webdriver classic#14025

Merged
christian-bromann merged 7 commits intowebdriverio:mainfrom
navin772:handle-window-classic
Jan 8, 2025
Merged

fix(webdriverio): better handle window switching in webdriver classic#14025
christian-bromann merged 7 commits intowebdriverio:mainfrom
navin772:handle-window-classic

Conversation

@navin772
Copy link
Contributor

@navin772 navin772 commented Jan 3, 2025

Proposed changes

Fixes #13989

Added an e2e test to test the changes for webdriver classic.

Types of changes

  • Polish (an improvement for an existing feature)
  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update (improvements to the project's docs)
  • Specification changes (updates to WebDriver command specifications)
  • Internal updates (everything related to internal scripts, governance documentation and CI files)

Checklist

  • I have read the CONTRIBUTING doc
  • I have added tests that prove my fix is effective or that my feature works
  • I have added the necessary documentation (if appropriate)
  • I have added proper type definitions for new commands (if appropriate)

Backport Request

//: # (The current main branch is the development branch for WebdriverIO v9. If your change should be released to the current major version of WebdriverIO (v8), please raise another PR with the same changes against the v8 branch.)

  • This change is solely for v9 and doesn't need to be back-ported
  • Back-ported PR at #XXXXX

Further comments

Reviewers: @webdriverio/project-committers

})

describe('handle windows in webdriver classic', () => {
it('should handle window closing and switching in WebDriver Classic mode', async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't test the newly added functionality. Can you add a test that verifies that we now automatically switch when closing a window?

Copy link
Contributor Author

@navin772 navin772 Jan 3, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this test be good enough?

describe('handle windows in webdriver classic', () => {
    it('should handle window closing and switching in WebDriver Classic mode', async () => {
        await browser.url('https://the-internet.herokuapp.com/iframe')
        const elementalSeleniumLink = await $('/html/body/div[3]/div/div/a')
        await elementalSeleniumLink.waitForDisplayed()
        await elementalSeleniumLink.click()
        await browser.waitUntil(async () => (await browser.getWindowHandles()).length === 2)
        await browser.switchWindow('https://elementalselenium.com/')
        await $('#__docusaurus_skipToContent_fallback').waitForDisplayed()
        await browser.closeWindow()

        const remainingWindows = await browser.getWindowHandles()
        expect(remainingWindows.length).toBe(1)
        await browser.switchWindow(remainingWindows[0])

        // Verify we're on the original window
        expect(await $('.example h3').getText()).toBe('An iFrame containing the TinyMCE WYSIWYG Editor')
    })
})

I have tested this PR with examples mentioned here and here and both of these are working after the changes.

if (!this.isBidi && (!currentWindow || !tabs.includes(currentWindow))) {
// Switch to the first available window before proceeding
await this.switchToWindow(tabs[0])
contextManager.setCurrentContext(tabs[0])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@christian-bromann correct me if I am wrong but the context manager is only used in BiDi right?

@pkg-pr-new
Copy link

pkg-pr-new bot commented Jan 3, 2025

Open in Stackblitz

eslint-plugin-wdio

npm i https://pkg.pr.new/webdriverio/webdriverio/eslint-plugin-wdio@14025

@wdio/allure-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/allure-reporter@14025

@wdio/browser-runner

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/browser-runner@14025

@wdio/appium-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/appium-service@14025

@wdio/browserstack-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/browserstack-service@14025

@wdio/cli

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/cli@14025

@wdio/concise-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/concise-reporter@14025

@wdio/config

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/config@14025

@wdio/cucumber-framework

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/cucumber-framework@14025

@wdio/dot-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/dot-reporter@14025

@wdio/firefox-profile-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/firefox-profile-service@14025

@wdio/globals

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/globals@14025

@wdio/jasmine-framework

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/jasmine-framework@14025

@wdio/json-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/json-reporter@14025

@wdio/junit-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/junit-reporter@14025

@wdio/lighthouse-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/lighthouse-service@14025

@wdio/local-runner

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/local-runner@14025

@wdio/logger

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/logger@14025

@wdio/mocha-framework

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/mocha-framework@14025

@wdio/protocols

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/protocols@14025

@wdio/repl

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/repl@14025

@wdio/reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/reporter@14025

@wdio/runner

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/runner@14025

@wdio/sauce-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/sauce-service@14025

@wdio/shared-store-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/shared-store-service@14025

@wdio/smoke-test-cjs-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/smoke-test-cjs-service@14025

@wdio/smoke-test-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/smoke-test-reporter@14025

@wdio/smoke-test-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/smoke-test-service@14025

@wdio/spec-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/spec-reporter@14025

@wdio/static-server-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/static-server-service@14025

@wdio/sumologic-reporter

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/sumologic-reporter@14025

@wdio/testingbot-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/testingbot-service@14025

@wdio/types

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/types@14025

@wdio/utils

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/utils@14025

@wdio/webdriver-mock-service

npm i https://pkg.pr.new/webdriverio/webdriverio/@wdio/webdriver-mock-service@14025

webdriver

npm i https://pkg.pr.new/webdriverio/webdriverio/webdriver@14025

webdriverio

npm i https://pkg.pr.new/webdriverio/webdriverio@14025

commit: 78b256a

@skamineni
Copy link

Thanks for fixing this issue. This has been a blocker for us to move to wdio9.5 version with 'wdio:enforceWebDriverClassic': true

@christian-bromann christian-bromann self-requested a review January 3, 2025 23:28
Copy link
Member

@christian-bromann christian-bromann left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for raising the PR @navin772 !

I tried to run your reproduction case:

    await browser.url('https://the-internet.herokuapp.com/iframe')
    const elementalSeleniumLink = await browser.$('/html/body/div[3]/div/div/a')
    await elementalSeleniumLink.waitForDisplayed()
    await elementalSeleniumLink.click()
    await browser.waitUntil(async () => (await browser.getWindowHandles()).length === 2)
    await browser.switchWindow('https://elementalselenium.com/')
    await browser.$('#__docusaurus_skipToContent_fallback').waitForDisplayed()
    await browser.closeWindow()

    const remainingWindows = await browser.getWindowHandles()
    console.log('remainingWindows.length', remainingWindows.length)
    await browser.switchWindow(remainingWindows[0])

    // Verify we're on the original window
    console.log(await browser.$('.example h3').getText())

on the current main (without your patch) and the script executed just fine with the following output:

remainingWindows.length 1
An iFrame containing the TinyMCE WYSIWYG Editor

So it seems like the patch you provided doesn't really catch the error you are trying to address. Can you provide an example for me to review this?

}

const currentWindow = await this.getWindowHandle()
const currentWindow = await this.getWindowHandle().catch(() => null)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In what cases do we expect the command not to be available?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe, when there is no active window or the context is not initialized properly. Although, I think BiDi is somehow handling these cases and thus we are seeing these issues in classic mode only.

@navin772
Copy link
Contributor Author

navin772 commented Jan 6, 2025

Can you provide an example for me to review this?

Hi @christian-bromann, thanks for reviewing, can you try this test as mentioned in #13882:

describe('open multiple tabs and closeWindow then switchWindow', function () {
  it('open multiple tabs and closeWindow then switchWindow', async function () {
    await browser.url('https://www.google.com/');
    await browser.newWindow('https://webdriver.io/docs/api/');
    await browser.newWindow('https://github.com/');
    await browser.pause(1000);
    await browser.closeWindow();
    await browser.switchWindow('google');

    /*
  //getting current handle also triggers the error
  let currentHandle = await browser.getWindowHandle();
  */
  });
});

@christian-bromann
Copy link
Member

@navin772 that is the behavior you are seeing and what is the expected behavior?

@navin772
Copy link
Contributor Author

navin772 commented Jan 6, 2025

@christian-bromann The behaviour we are currently seeing is that after we call closeWindow() there is no valid window handle returned and thus the next switchWindow() command fails with the following error:

[0-0] 2025-01-06T18:46:28.564Z INFO webdriver: COMMAND closeWindow()
[0-0] 2025-01-06T18:46:28.565Z INFO webdriver: [DELETE] http://localhost:55251/session/5f3b749110d10d581bcd89c0d078347f/window
[0-0] 2025-01-06T18:46:28.686Z INFO webdriver: RESULT [
[0-0]   'D503F2353D842B12EB85F4B09D4CB6E3',
[0-0]   '51CAD7E3511A5AB997D643158BF4ED19'
[0-0] ]
[0-0] 2025-01-06T18:46:28.688Z INFO webdriver: COMMAND getWindowHandle()
[0-0] 2025-01-06T18:46:28.689Z INFO webdriver: [GET] http://localhost:55251/session/5f3b749110d10d581bcd89c0d078347f/window
[0-0] 2025-01-06T18:46:28.707Z WARN webdriver: WebDriverError: no such window: target window already closed
[0-0] from unknown error: web view not found
[0-0]   (Session info: chrome=131.0.6778.205) when running "window" with method "GET"
[0-0] 2025-01-06T18:46:28.708Z INFO webdriver: Retrying 1/3

The fix catches this no such window error. The expected behaviour is that we can switch to another open window after closing a window in classic mode.

@christian-bromann
Copy link
Member

@navin772 what capabilities are you using?

@navin772
Copy link
Contributor Author

navin772 commented Jan 7, 2025

@christian-bromann the caps:

capabilities: [
    {
      browserName: 'chrome',
      "wdio:enforceWebDriverClassic": true,
     },
  ]

Copy link
Member

@christian-bromann christian-bromann left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took another look at this matter I propose a different solution. We introduced the context manager to deal with window changes and mitigating issues as seen in the reported bug. This change will provide the same mitigation for both modes: classic and bidi:

diff --git a/packages/webdriverio/src/context.ts b/packages/webdriverio/src/context.ts
index 176f710af..7b2bed7a8 100644
--- a/packages/webdriverio/src/context.ts
+++ b/packages/webdriverio/src/context.ts
@@ -36,6 +36,21 @@ export class ContextManager {
             isNativeContext: this.#isNativeContext
         })

+        /**
+         * Listens for the 'closeWindow' browser command to handle context changes.
+         * (classic + bidi)
+         */
+        this.#browser.on('result', (event) => {
+            /**
+             * the `closeWindow` command returns:
+             *   > the result of running the remote end steps for the Get Window Handles command, with session, URL variables and parameters.
+             */
+            if (event.command === 'closeWindow') {
+                this.#currentContext = (event.result as { value: string[] }).value[0]
+                return this.#browser.switchToWindow(this.#currentContext)
+            }
+        })
+
         if (!this.#isEnabled()) {
             return
         }
@@ -77,15 +92,6 @@ export class ContextManager {
          * Listens for the 'closeWindow' browser command to handle context changes.
          */
         this.#browser.on('result', (event) => {
-            /**
-             * the `closeWindow` command returns:
-             *   > the result of running the remote end steps for the Get Window Handles command, with session, URL variables and parameters.
-             */
-            if (event.command === 'closeWindow') {
-                this.#currentContext = (event.result as { value: string[] }).value[0]
-                return this.#browser.switchToWindow(this.#currentContext)
-            }
-
             if (this.#browser.isMobile) {
                 if (event.command === 'getContext') {
                     this.setCurrentContext((event.result as { value: string }).value)

@navin772
Copy link
Contributor Author

navin772 commented Jan 8, 2025

@christian-bromann this is a much better approach handling both bidi and classic. I have tested this out and will update it accordingly.

Thanks for the suggestions!

@christian-bromann christian-bromann added the PR: Bug Fix 🐛 PRs that contain bug fixes label Jan 8, 2025
Copy link
Member

@christian-bromann christian-bromann left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍 thanks a lot!

@christian-bromann christian-bromann merged commit 409bfce into webdriverio:main Jan 8, 2025
@skamineni
Copy link

skamineni commented Jan 8, 2025

Thank you guys so much for the fix @navin772 and @christian-bromann ! so we need to pull new version of wdio to see this bug fixed right ? i.e 9.5.3 or so ?

@christian-bromann
Copy link
Member

Yes, this will be out with the next patch release. I will trigger the pipeline now.

@skamineni
Copy link

Yes, this will be out with the next patch release. I will trigger the pipeline now.

Thanks!

@navin772 navin772 deleted the handle-window-classic branch January 9, 2025 03:14
@HannaTarasevich
Copy link
Contributor

Hi @navin772,
Today we've updated to the latest WDIO (9.5.1 --> 9.5.2) and our closeWindow() command stopped working due to the error:
image

We had to downgrade the version due to this issue. If I find any reproducible example, I'll share it via a new bug.

@christian-bromann
Copy link
Member

Today we've updated to the latest WDIO (9.5.1 --> 9.5.2) and our closeWindow() command stopped working due to the error:

This is a regression in Chrome as reported in referenced issue.

@HannaTarasevich
Copy link
Contributor

@christian-bromann Could you please share if this is the Chrome issue, why downgrade to 9.5.1 WDIO helped for the case with "wdio: enforceWebDriverClassic: true"? I didn't get it

@christian-bromann
Copy link
Member

Oh, this is probably a regression then that resulted from this PR. We should check in the event listener whether there are contexts available and create one in case there aren't any.

@navin772 @HannaTarasevich you want to take a stab at this fixing it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

PR: Bug Fix 🐛 PRs that contain bug fixes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multi tabs, after calling closeWindow , switchWindow fails with 'WebDriverError: no such window: target window already closed

5 participants