title: Reattach to existing chrome session with headless chrome in Selenium?
body: <p>I'm trying to re-attach to existing Chrome session, with user-data-dir chrome_option. While it works with non-headless, it doesn't do anything when in headless mode.
  It worked a couple of months ago, following this guide: <a href="https://stackoverflow.com/questions/46409171/i-can-reattach-to-session-with-selenium-but-cannot-stop-it-launching-another-bro">I can reattach to session with selenium but cannot stop it launching another browser?</a> , but not any more.
  Any clues on how to do it?</p>
  <p>Here is my code:</p>
  <pre><code>executor_url = driver2.command_executor._url
  session_id = driver2.session_id
  time.sleep(2)
  
  driver2.get(&quot;https://www.google.com&quot;)
  print(driver2.current_url)
  time.sleep(5)
  driver2.get_screenshot_as_file('capture0.png')
  
  def create_driver_session(session_id, executor_url):
      from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
  
      # Save the original function, so we can revert our patch
      org_command_execute = RemoteWebDriver.execute
  
      def new_command_execute(self, command, params=None):
          if command == &quot;newSession&quot;:
              # Mock the response
              return {'success': 0, 'value': None, 'sessionId': session_id}
          else:
              return org_command_execute(self, command, params)
  
      # Patch the function before creating the driver object
      RemoteWebDriver.execute = new_command_execute
  
      new_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
      new_driver.session_id = session_id
  
      # Replace the patched function with original function
      RemoteWebDriver.execute = org_command_execute
  
      return new_driver
  
  driver2 = create_driver_session(session_id, executor_url)
  print(driver2.current_url)
  </code></pre>
  <p>Thanks!</p>