How to click Allow on Show Notifications popup using Selenium Webdriver
Asked Answered
B

9

61

I'm trying to login to Facebook. After a successful login, I get a browser popup:

Show Notifications

How with the webdriver can I click Allow and proceed forward?

Boanerges answered 31/7, 2016 at 12:53 Comment(4)
make it manually allow onesUrson
right now i am doing the same! but is there no way to make selenium do it?Boanerges
If you don't necessarily need to "Allow", but just want to get rid of the dialog, you can also just simulate the escape key, which will dismiss the dialog. new Actions().sendKeys(Keys.ESCAPE).build().perform();Standee
browser.keys("Escape"); // Dismiss "notifications" dialog box. Matthijs, that works!Hyperbole
M
76

Please Follow below steps :

A) USING JAVA :

For Old Chrome Version (<50):

//Create a instance of ChromeOptions class
ChromeOptions options = new ChromeOptions();

//Add chrome switch to disable notification - "**--disable-notifications**"
options.addArguments("--disable-notifications");
        
//Set path for driver exe 
System.setProperty("webdriver.chrome.driver","path/to/driver/exe");

//Pass ChromeOptions instance to ChromeDriver Constructor
WebDriver driver =new ChromeDriver(options);

For New Chrome Version (>50):

//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);

For Firefox :

WebDriver driver ;
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("permissions.default.desktop-notification", 1);
DesiredCapabilities capabilities=DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
driver = new FirefoxDriver(capabilities);
driver.get("http://google.com");

B) USING PYTHON :

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

option = Options()

option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument("--disable-extensions")

# Pass the argument 1 to allow and 2 to block
option.add_experimental_option(
    "prefs", {"profile.default_content_setting_values.notifications": 1}
)

driver = webdriver.Chrome(
    chrome_options=option, executable_path="path-of-driver\chromedriver.exe"
)
driver.get("https://www.facebook.com")

C) USING C#:

ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-notifications"); // to disable notification
IWebDriver driver = new ChromeDriver(options);
Moonrise answered 12/10, 2016 at 11:30 Comment(4)
this works for older versions of chromedriver. (Chrome 49 compatible ones...) This does not work for later versions. Not sure when the cutoff was, but for the latest version you need to use the prefs HashMap option. Saurabh Gaur's answer.Ingles
the question is about how to ALLOW by default, the profile.default_content_setting_values.notifications=2 will DISALLOW by default, to ALLOW it should be profile.default_content_setting_values.notifications=1Chainplate
How to do this for safari?Gytle
This is so neat that you have provided the 3 common most languages used for selenium.Sachsen
C
15
import unittest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time


class SendMsgSkype(unittest.TestCase):

    @classmethod
    def setUpClass(cls):

        options = Options()
        options.add_argument("--disable-notifications")

        cls.driver = webdriver.Chrome("./chromedriver.exe", chrome_options=options)

        cls.driver.implicitly_wait(5)
        cls.driver.maximize_window()
        cls.driver.get("https://web.skype.com/ru/")

It works for me. More details here: http://nullege.com/codes/show/src@t@a@[email protected]/21/selenium.webdriver.Chrome

Crapulous answered 24/1, 2017 at 11:47 Comment(1)
This works for me, using Python 3.7 and latest selenium in Feb 2019. For the noobish like me, and also if you are using selenium to scrape some results after login (consensus seems use requests package unless you need login / click buttons), rather than testing webpages, key lines are: from selenium import webdriver....options = webdriver.ChromeOptions() options.add_argument("--disable-notifications") driver = webdriver.Chrome("path/to/ChromeDriver.exe", options= options) or as OP wanted in fact to enable notifications, presumably ("--enable-notifications") is the main alternative.Kinsella
H
12

This not an alert box, so you can't handle it using Alert, this is a chrome browser notification, To Switch off this browser notification you need to create chrome preference map with chrome option as below :

//Create prefs map to store all preferences 
Map<String, Object> prefs = new HashMap<String, Object>();
    
//Put this into prefs map to switch off browser notification
prefs.put("profile.default_content_setting_values.notifications", 2);

//Create chrome options to set this prefs
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
    
//Now initialize chrome driver with chrome options which will switch off this browser notification on the chrome browser
WebDriver driver = new ChromeDriver(options);

//Now do your further steps

Hope it helps..:)

Hannahannah answered 2/8, 2016 at 5:59 Comment(0)
A
8

The one and only working solution I've come across so far is this:

from selenium.webdriver.chrome.options import Options

chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
Arce answered 10/6, 2017 at 9:44 Comment(1)
doesn't work, check this #51441182Blackball
H
2

no answer has been accepted yet, this following code works for me

ruby, rspec, capybara

Capybara.register_driver :selenium_chrome do |app|
  prefs = {"profile.managed_default_content_settings.notifications" => 2,}
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(chrome_options: { prefs: prefs })

  Capybara::Selenium::Driver.new(app, browser: :chrome, desired_capabilities: caps)
end

Capybara.javascript_driver = :selenium_chrome
Humanoid answered 24/8, 2017 at 9:49 Comment(0)
U
1
try {

   // Check the presence of alert
   Alert alert = driver.SwitchTo().Alert();

   // if present consume the alert
   alert.Accept();

  } catch (NoAlertPresentException ex) {
     //code to do if not exist.
  }
Urson answered 1/8, 2016 at 4:44 Comment(0)
H
1

Facebook authentication window displays an overlay that covers the continue as [username] button.

enter image description here

This makes the continue button un-clickable. To circumvent that problem, you can hide those layers programmatically using JavaScript (not recommended) using this code (don't do this).

  // DO NOT USE THIS CODE.
  function forceClickSetup(targetSelector) {
      return browser.selectorExecute("div", 
      function(divs, targetSelector) {
        var button = document.querySelector(targetSelector);
        for(var i = 0; i < divs.length; i++) {
          if(!divs[i].contains(button)) {
            divs[i].remove();
          }
        }
        return i;
    }, targetSelector);
  }

Or instead, you can dismiss the notifications dialog, after which facebook will uncover the continue button. But before wildly hitting Escape at the browser, first make sure that the continue button has been shown.

// USE THIS CODE.
browser.waitForVisible("[name=__CONFIRM__]");
browser.keys("Escape"); // Dismiss "notifications" dialog box.

var confirmButtonSelector = "[name=__CONFIRM__]";

This solution is really Matthijs' (see comments above)

Hyperbole answered 19/2, 2018 at 19:38 Comment(2)
What is browser in this instance?Demanding
Thanks, Exactly what I needed .It's Chrome if anyone like @Roymunson wants to knowEvangelia
U
0

if you play with Ruby and Capybara try this code

    Capybara.register_driver :chrome_no_image_popup_maximize do |app|
    # 2: disable, other than 2 means enable it
    preferences = {
        "profile.managed_default_content_settings.notifications" => 2,
        "profile.managed_default_content_settings.images" => 2,
        "profile.managed_default_content_settings.popups" => 2   
    }

    caps = Selenium::WebDriver::Remote::Capabilities.chrome( 
        'chromeOptions' => {
            'prefs' => preferences, 
        } 
    )

    args = [ "--start-maximized" ]

    Capybara::Selenium::Driver.new(app, {:browser => :chrome, :desired_capabilities => caps, :args => args})
end

Capybara.default_driver = :chrome_no_image_popup_maximize
Capybara.javascript_driver = :chrome_no_image_popup_maximize
Unreligious answered 26/12, 2017 at 22:2 Comment(0)
C
0

if you are using selenium - 4 you can apply these changes to handle such issues. It worked perfectly for me.

    public WebDriver openBrowser() {
    if (driver == null) {
        String browserType = myProp.getProperty("browser");
        System.out.println(browserType);

        if (browserType.equalsIgnoreCase("chrome")) {
            // Create ChromeOptions
            ChromeOptions options = new ChromeOptions();
            options.addArguments("--disable-notifications");
            options.addArguments("--disable-popup-blocking");
            options.addArguments("--no-sandbox");
            options.addArguments("--disable-dev-shm-usage");

            // Add geolocation permission
            options.addArguments("--enable-geolocation");

            // Initialize Chrome driver with options
            driver = new ChromeDriver(options);

        } else if (browserType.equalsIgnoreCase("firefox")) {
            // Create Firefox profile
            FirefoxProfile profile = new FirefoxProfile();
            profile.setPreference("geo.enabled", true);
            profile.setPreference("geo.provider.use_corelocation", true);
            profile.setPreference("geo.prompt.testing", true);
            profile.setPreference("geo.prompt.testing.allow", true);

            // Initialize FirefoxOptions
            FirefoxOptions options = new FirefoxOptions();
            options.setProfile(profile);

            // Initialize Firefox driver with options
            driver = new FirefoxDriver(options);
        }
    }
    return driver;
}

}

Chequered answered 18/9, 2023 at 10:25 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Worried

© 2022 - 2024 — McMap. All rights reserved.