Selenium addCookie getting Invalid Cookie Domain Exception even though I'm on the right domain
Asked Answered
H

3

5

So I'm trying to load previously saved cookies into my web driver with Selenium/Geb. First I goto the domain and then try to add the cookies. But the cookie domain and the url domain don't register with each other:

Caught: org.openqa.selenium.InvalidCookieDomainException: 
You may only add cookies that would be visible to the current domain: .domain=.example.com => .www.example.com
Build info: version: '2.35.0', revision: '8df0c6bedf70ff9f22c647788f9fe9c8d22210e2', time: '2013-0  8-17 12:46:41'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '3.2.0-48-generic', java.version:   '1.6.0_27'
Driver info: driver.version: unknown

It seems the cookie's domain is .example.com and the domain I get to when I go to http://example.com is .www.example.com. The only solution I can think of is overriding some method to spoof my current domain, but I have no idea how to go about that.

Herve answered 3/10, 2013 at 0:37 Comment(3)
Show me, how you set cookies? Code please.Fachanan
I am having the same issue. Any clues?Elvyn
see also How to preload cookies before first request with Python3, Selenium Chrome WebDriver?Rye
O
1

I had a somewhat similar problem where I was getting the "You may only set cookies for the current domain" error for no apparent reason.

I solved it by striping the cookie of all the parameters except name and value:

(Python)

cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    print cookie
    new_cookie={}
    new_cookie['name']=cookie['name']
    new_cookie['value']=cookie['value']
    driver.add_cookie(new_cookie)
Operation answered 9/11, 2014 at 23:47 Comment(1)
This may not work for servers that validate the domain of the cookie - if the server is expecting the cookie's domain to be .www.server.com and you let the browser clobber it with www.server.com, the server might reject or ignore it.Roma
P
1

Before (with problem):

driver = webdriver.Chrome(service=service, options=options)

for cookie in exported_cookies:
    driver.add_cookie(cookie)

driver.get(url)

After (without problem):

driver = webdriver.Chrome(service=service, options=options)

driver.get(url) # Add driver.get() before set cookie 

for cookie in exported_cookies:
    driver.add_cookie(cookie)

driver.get(url)
Presley answered 2/9, 2023 at 22:18 Comment(0)
B
0

Issue is old and maybe the answer given used to work, but with Selenium 3.140.0, stripping the domain and only adding the name and value will still throw an invalid cookie domain exception.

What worked for me was to browser.get and then perform the browser.add_cookie using the same domain for the page that was loaded.

I confirmed this using session cookies to bypass a login page.

Berghoff answered 11/2, 2021 at 14:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.