Java Selenium中禁用Chrome實驗性選項same-site-by-default-cookies和cookies-without-same-site-must-be-secure
背景:
Selenium + Java 實現(xiàn)UI自動化,發(fā)現(xiàn)登錄后,進不了主界面,還是調(diào)回登錄頁,前臺報錯401,后臺日志沒發(fā)現(xiàn)問題chrome版本 86.0.4240.111(正式版本) (64 位),查資料可知,原來Chrome?51?開始,瀏覽器的Cookie新增加了一個SameSite屬性,用來防止CSRF?攻擊和用戶追蹤。但是我們開發(fā)時,少不了跨域啊,上網(wǎng)找了一下資料,有以下解決方法
方法一:
在chrome瀏覽器的地址欄輸入:chrome://flags/?;然后在搜索框輸入:SameSite?將SameSite by?default?cookies 和?Cookies without SameSite must be secure 狀態(tài)都改為:desabled;設(shè)置后點擊“relaunch”按鈕生效


然后重新打開網(wǎng)址,登錄,發(fā)現(xiàn)可以登錄后跳轉(zhuǎn),接著運行UI 自動化代碼,發(fā)現(xiàn)還是無法登錄,重新查看SameSite設(shè)置,發(fā)現(xiàn)已被重置;沒辦法,查閱資料后,只能代碼中解決;
方法二:
代碼中設(shè)置:
//設(shè)置chrome跨域
ChromeOptions options=new ChromeOptions();
options.addArguments("--args --disable-web-security --user-data-dir");
driver=new ChromeDriver(options);
Log.info("初始化chrome瀏覽器");
再次運行,還是無法實現(xiàn)登錄后跳轉(zhuǎn);
方法三:
那么,如何在Java Selenium中禁用Chrome實驗性選項
same-site-by-default-cookies和cookies-without-same-site-must-be-secure?可以使用same-site-by-default-cookies@2&禁用cookies-without-same-site-must-be-secure@
代碼如下:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setHeadless(false);//true不打開頁面,false打開頁面
HashMap<String, Object> chromeLocalStatePrefs = new HashMap<String, Object>();
List<String> experimentalFlags = new ArrayList<String>();
experimentalFlags.add("same-site-by-default-cookies@2");
experimentalFlags.add("cookies-without-same-site-must-be-secure@2");
chromeLocalStatePrefs.put("browser.enabled_labs_experiments", experimentalFlags);
chromeOptions.setExperimentalOption("localState", chromeLocalStatePrefs);
再次運行,終于實現(xiàn)登錄后跳轉(zhuǎn);

浙公網(wǎng)安備 33010602011771號