首页 > 解决方案 > chromeWebdriver - 当我将 Chrome 更新到 77 时无法设置 cookie

问题描述

我将 Chrome 和 chromewebdriver 更新到版本 77。在此之后,unable to set cookie当我addCookie.

System.setProperty("cookie", "auth=ok,path=/");
int indexValue = cookieStr.indexOf('=');
int indexPath = cookieStr.indexOf(",path=");
String cookieName = cookieStr.substring(0, indexValue);
String cookieValue = cookieStr.substring(indexValue + 1, indexPath);
String cookieDomain = new URI("http://localhost").getHost().replaceAll("self.", "");
String cookiePath = cookieStr.substring(indexPath + 6);
Cookie authCookie= new Cookie.Builder(cookieName, cookieValue).domain(cookieDomain).path(cookiePath).expiresOn(new SimpleDateFormat("dd/MM/yyyy").parse("31/12/2020")).build();
System.out.println("A");
driver.navigate().to("http://localhost:8000/unprotected");
System.out.println("B");
driver.get("http://localhost:8000/404");
System.out.println("C");
System.out.println("[" + driver.getPageSource()+"]");
Options b = a.manage();
System.out.println("Domain: " + cookie.getDomain());
System.out.println("Name: " + cookie.getName());
System.out.println("Path: " + cookie.getPath());
System.out.println("Value: " + cookie.getValue());
System.out.println("Expiry: " + cookie.getExpiry());
b.addCookie(cookie);   <= KO
System.out.println("D");

安慰:

A
B
C
[<html><head></head><body><h1>404 Not Found</h1>No context found for request</body></html>]
Domain: localhost
Name: auth
Path: /
Value: ok
Expiry: Thu Dec 31 00:00:00 CET 2020

错误:

org.openqa.selenium.UnableToSetCookieException: unable to set cookie
  (Session info: chrome=77.0.3865.75)
Build info: version: '3.12.0', revision: '7c6e0b3', time: '2018-05-08T14:04:26.12Z'
System info: host: 'xxxxxxxxx', ip: '192.168.0.111', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_201'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 77.0.3865.75, chrome: {chromedriverVersion: 77.0.3865.40 (f484704e052e0..., userDataDir: C:\Users\JFTS8586\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:58344}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: accept}
Session ID: 82305922f96631ac61d95a737263cb64]

如果您想在本地计算机上重现此问题,则此处(在一类中)在线提供完整代码。

铬团队的更多信息在这里

标签: javaseleniumselenium-chromedriver

解决方案


您可以尝试使用127.0.0.1而不是localhost.

Chrome 不再支持在本地主机上设置域 cookie。如果您从 cookie 设置中删除域,它应该可以正常工作。

更多细节:

当前的 WebDriver 标准并不清楚应该如何处理 cookie 域。ChromeDriver 的实现尝试遵循https://www.rfc-editor.org/rfc/rfc6265#section-5.3。根据 cookie 存储模型的第 6 项,指定 cookie 域会导致域 cookie,而不指定域会导致仅主机 cookie。但是,为 localhost 创建域 cookie 并没有真正意义,因为 localhost 不遵循域命名约定。Chrome 过去对此很宽容,但 Chrome 77 现在有代码拒绝为 localhost 创建域 cookie,因此不再允许为 localhost cookie 指定域。


推荐阅读