Ajay Kumar

Ajay Kumar

  • 52
  • 29.1k
  • 1.6m

Selenium C# WebDriver Get the Browser is opened with Session or not

Apr 15 2024 6:45 AM
   public static WebDriver getWebDriver(string Sessionid)
   {    
       try
       {
               ChromeOptions chromeOptions = new ChromeOptions();
               var FolderPathToStoreSession = @"C:\Session\" + Sessionid;
               chromeOptions.AddArguments("--window-size=1920,1080");
               chromeOptions.AddArguments("--disable-gpu");
               chromeOptions.AddArguments("--disable-extensions");
               chromeOptions.AddArguments("--no-sandbox");
               chromeOptions.AddArguments("--disable-dev-shm-usage");
               chromeOptions.AddArguments("--disable-setuid-sandbox");
               chromeOptions.AddArguments("--disable-features=RendererCodeIntegrity");
               chromeOptions.AddArguments("--disable-features=VizDisplayCompositor");
               chromeOptions.AddArguments("--disable-features=NetworkService");
               chromeOptions.AddArguments("--disable-features=NetworkServiceInProcess");
               chromeOptions.AddArguments("--start-maximized");
               chromeOptions.AddArguments("chrome.switches", "--disable-extensions");
               chromeOptions.AddArgument("--user-data-dir=" + FolderPathToStoreSession);

               chromewebDriver = new ChromeDriver(chromeOptions);
               return chromewebDriver;
       }
       catch(Exception ex)
       {
       }
       return chromewebDriver;
   }

Using This Code I Have Saved the Website Session using this line of Code

chromeOptions.AddArgument("--user-data-dir=" + FolderPathToStoreSession);

It Working Fine , if I pass the Session ID in this

  getWebDriver(string Sessionid) 

Then it opened a new browser and it Working Fine but the Issue is When I use the Same Session id AGain then it Gives an Exception 

Opening in existing browser session.

session not created: Chrome failed to start: exited normally.
  (session not created: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.) (SessionNotCreated)

if it Gives an Exception THen I Handle using try catch but the issue is it open a browser again see in below Screenshot

it Gives Error and open new browser 

I Want to if the below code gives error then no browser opened.

                    chromewebDriver = new ChromeDriver(chromeOptions);

 


Answers (2)