'getting Invalid session id when trying to close the webdriver browser

In Jmeter webdriver sampler when I try to close the browser with the below code I am getting an invalid session id and my test gets failed. This error is gone when I comment out that browser.close() line. But I want to make sure the browser is closed after my test is done so it can give some space in the RAM.

At the very end of the test I am calling this logout script

var selenium = org.openqa.selenium
var support_ui=JavaImporter(org.openqa.selenium.support.ui) 
var EC = org.openqa.selenium.support.ui.ExpectedConditions

WDS.sampleResult.sampleStart()
-- some code
logout()
WDS.sampleResult.sampleEnd()

function logout(){
    var logoutBtn = waitByElement(selenium.By.cssSelector("button[title='User Options']"), EC.elementToBeClickable, 30)
    logoutBtn.click();
    WDS.browser.findElement(selenium.By.cssSelector("button[data-testid='logout']")).click();
    var userNameField = waitByElement(selenium.By.xpath("//*[contains(text(),'Disclaimer')]"), EC.presenceOfElementLocated, 60)
    takeScreenshot('screenshot_loggedout')
    WDS.browser.close()
}

Error in the console.

2022-04-01 12:15:19,543 INFO o.a.j.t.JMeterThread: Thread is done: Upload Email batches 2-7
2022-04-01 12:15:19,543 INFO o.a.j.t.JMeterThread: Thread finished: Upload Email batches 2-7
2022-04-01 12:15:22,034 INFO c.g.j.p.w.s.WebDriverSampler: Taking screenshots for: screenshot_loggedout
2022-04-01 12:15:22,385 ERROR c.g.j.p.w.s.WebDriverSampler: invalid session id
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:19:58.91Z'
System info:os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_321'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 99.0.4844.84, chrome: {chromedriverVersion: 99.0.4844.51 (d537ec02474b5..., userDataDir:  goog:chromeOptions: {debuggerAddress: localhost:64044}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(direct), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify, webauthn:extension:credBlob: true, webauthn:extension:largeBlob: true, webauthn:virtualAuthenticators: true}
Session ID: cfd685ceaf0be8c1b5c32d453ef3da97


Solution 1:[1]

Just remove WDS.browser.close() statement, the WebDriver instance is getting closed automatically when the thread is being ended, there is no need to close/exit the browser.

More information: The WebDriver Sampler: Your Top 10 Questions Answered

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitri T