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

如何使用Selenium禁用Firefox和Chrome推送通知?Firefox旧方法失效

我来帮你解决这个问题!针对你使用的Selenium 3.11.0版本,下面分别给出Chrome和Firefox禁用推送通知的有效配置,特别是Firefox旧方案失效后的替代方案:

Chrome 禁用推送通知配置

Chrome的方案你之前应该已经试过且生效了,这里再整理一下标准写法,确保兼容性:

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

public class ChromeNotificationDisable {
    public static void main(String[] args) {
        // 设置ChromeDriver路径(如果没配置环境变量的话)
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        
        ChromeOptions options = new ChromeOptions();
        Map<String, Object> prefs = new HashMap<>();
        // 2表示拒绝所有通知请求
        prefs.put("profile.default_content_setting_values.notifications", 2);
        options.setExperimentalOption("prefs", prefs);
        
        WebDriver driver = new ChromeDriver(options);
        // 后续操作...
    }
}
Firefox 禁用推送通知配置(弃用方案替代)

你提到之前的Firefox方案已失效,这大概率是因为旧版本依赖直接传入FirefoxProfile的方式已被逐步弃用,或者对应的偏好参数需要调整。下面是适配Selenium 3.11.0的有效配置:

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

public class FirefoxNotificationDisable {
    public static void main(String[] args) {
        // 设置GeckoDriver路径(如果没配置环境变量的话)
        System.setProperty("webdriver.gecko.driver", "path/to/geckodriver");
        
        FirefoxOptions options = new FirefoxOptions();
        // 禁用网页通知
        options.addPreference("dom.webnotifications.enabled", false);
        // 禁用推送服务
        options.addPreference("dom.push.enabled", false);
        // 拒绝所有桌面通知权限请求
        options.addPreference("permissions.default.desktop-notification", 2);
        
        WebDriver driver = new FirefoxDriver(options);
        // 后续操作...
    }
}

额外注意事项

  • 确保你的GeckoDriver版本和Firefox浏览器版本兼容:Selenium 3.11.0建议搭配GeckoDriver v0.20.0左右,避免因版本不匹配导致配置不生效。
  • 如果之前的代码是直接使用new FirefoxDriver(profile),请改为用FirefoxOptions封装Profile后传入,这是Selenium 3+推荐的写法:
    FirefoxProfile profile = new FirefoxProfile();
    profile.setPreference("dom.webnotifications.enabled", false);
    profile.setPreference("dom.push.enabled", false);
    profile.setPreference("permissions.default.desktop-notification", 2);
    
    FirefoxOptions options = new FirefoxOptions().setProfile(profile);
    WebDriver driver = new FirefoxDriver(options);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:29:35