You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Chrome中运行禁用第三方Cookie的Java Selenium测试?

可行,以下是验证有效的Java实现示例

核心方案

Chrome目前支持通过命令行启动参数直接禁用第三方Cookie,这是官方推荐的稳定方案,替代了已废弃的旧版偏好配置(如profile.default_content_settings.cookies)。

代码实现

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class ThirdPartyCookiesDisabledTest {
    public static void main(String[] args) {
        ChromeOptions options = new ChromeOptions();
        // 添加禁用第三方Cookie的启动参数
        options.addArguments("--disable-third-party-cookies");
        
        WebDriver driver = new ChromeDriver(options);
        
        // 此处编写你的测试逻辑
        driver.get("https://example.com");
        // ...
        
        driver.quit();
    }
}

动态配置备选方案(CDP方式)

如果需要在测试过程中动态切换第三方Cookie策略,可以使用Chrome DevTools Protocol(CDP)命令:

import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Map;

// 初始化driver后执行
((ChromeDriver) driver).executeCdpCommand(
    "Storage.setThirdPartyCookieBlocking",
    Map.of("blockThirdPartyCookies", true)
);

关于旧方法失效的说明

你提到的profile.default_content_settings.cookies设置失效,是因为Chrome的设置架构更新,这类旧的用户偏好键已被官方移除,不再生效。

你提供的参考资源翻译:

    1. 《在禁用Cookie的情况下运行Selenium》(SmartBear):介绍Selenium自动化测试中配置浏览器禁用Cookie的方案
    1. Reddit问题:有其他用户也遇到了相同的配置不生效问题

内容的提问来源于stack exchange,提问作者user622511

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 08:37:04