Passing SameSite Chrome Flags to Selenium remote server

Viewed 2934

I am running automated tests on a Selenium remote server in Python. The remote Selenium server runs inside of a docker container. I obtain my Selenium driver with the following code:

options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Remote(command_executor='http://127.0.0.1/wd/hub', options=options)
driver.get('http://127.0.0.1:8000')
# ...
driver.close()

I would like to pass two Chrome flags (#same-site-by-default-cookies and #cookies-without-same-site-must-be-secure) to the Selenium Chrome instance. After some research, it seems that I would pass these flags to a new Chrome process by running:

/usr/bin/google-chrome-stable --flag-switches-begin --disable-features=CookiesWithoutSameSiteMustBeSecure,SameSiteByDefaultCookies --flag-switches-end

I've tried adding these arguments to the Selenium ChromeOptions object like so:

options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("--flag-switches-begin")
options.add_argument("--disable-features=CookiesWithoutSameSiteMustBeSecure,SameSiteByDefaultCookies")
options.add_argument("--flag-switches-end")
# ... snip ...

Unfortunately, this doesn't appear to have any effect on the Selenium Chrome browser instance. How can I reconfigure the Selenium browser with these flags? Do I need to pass these arguments to the docker container somehow?

2 Answers

I think this line is not doing what you expect options.add_argument("--disable-features=CookiesWithoutSameSiteMustBeSecure,SameSiteByDefaultCookies")

CookiesWithoutSameSiteMustBeSecure vs. cookies-without-same-site-must-be-secure

Set your chrome options like this:

from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
# experimentalFlags = ['CookiesWithoutSameSiteMustBeSecure','SameSiteByDefaultCookies']
flags_i_want = ['cookies-without-same-site-must-be-secure@1', 'same-site-by-default-cookies@1']
chromeLocalStatePrefs = { 'browser.enabled_labs_experiments': flags_i_want}
chrome_options.add_experimental_option('localState',chromeLocalStatePrefs)
driver = webdriver.Chrome(executable_path=r'C:\\Path\\To\\chromedriver.exe', options=chrome_options)

driver.get("https://www.google.com")

I got this working with Jortega's help. The following code disables the SameSite experimental Chrome flags on a remote Selenium server as desired:

options = webdriver.ChromeOptions()

# Disable experimental features:
chrome_local_state_prefs = {
    "browser": {
        "enabled_labs_experiments": [
            "cookies-without-same-site-must-be-secure@2",
            "same-site-by-default-cookies@2",
        ],
    }
}
options.add_experimental_option("localState", chrome_local_state_prefs)

driver = webdriver.Remote(command_executor='http://127.0.0.1/wd/hub', options=options)
driver.get('http://127.0.0.1:8000')
# ...
driver.close()
Related