首页 > 解决方案 > 使用 selenium-webdriver 自动登录 Facebook 后无法通过 Google Chrome 的警报。语言是 Javascript / JS

问题描述

const {Builder, By, Key} = require('selenium-webdriver');
const {Options} = require('selenium-webdriver/chrome');

const options = new Options().setAlertBehavior('dismiss');
let driver = new Builder().forBrowser('chrome').setChromeOptions(options).build();
driver.get('https://www.facebook.com/');

(async function demo() {
    (await driver).findElement(By.css('#email')).sendKeys('***');
    (await driver).findElement(By.css('#pass')).sendKeys('***', Key.RETURN);    
})();

/* 仍然会弹出警报。问题是如何更改 Chrome 的 Options() 以使“www.facebook.com 想要向您显示通知”警报不再显示/可以自动接受/阻止?
谢谢!*/

标签: javascriptseleniumgoogle-chromeselenium-webdriveralert

解决方案


尝试这个

//Create a map to store  preferences 
Map<String, Object> prefs = new HashMap<String, Object>();

//add key and value to map as follow to switch off browser notification
//Pass the argument 1 to allow and 2 to block
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create an instance of ChromeOptions 
ChromeOptions options = new ChromeOptions();

// set ExperimentalOption - prefs 
options.setExperimentalOption("prefs", prefs);

//Now Pass ChromeOptions instance to ChromeDriver Constructor to initialize chrome driver which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

或者

Create a instance of ChromeOptions class

ChromeOptions options = new ChromeOptions();
Then Add chrome switch to disable notification - "--disable-notifications"

options.addArguments("--disable-notifications");
After that set path for driver exe

System.setProperty("webdriver.chrome.driver","path/to/driver/exe");
and then pass ChromeOptions instance to ChromeDriver Constructor

WebDriver driver =new ChromeDriver(options);

推荐阅读