Skip to main content
Introducing support for Selenium 4 and its BiDi APIs on BrowserStack Automate! Learn More!

Handle pop-ups, permissions, and notifications

Learn how to manage pop-ups, permissions, and notifications in different browsers when running your Selenium tests on BrowserStack Automate.

Introduction

When testing any web application, you might encounter certain advertisement pop-ups, notifications, or permission pop-ups for camera or microphones. This guide provides code samples and solutions to handle such pop-ups when testing your application.

Some of the most common pop-ups seen in both desktop and mobile devices are as follows -

Type of pop-up Description Reference    
Web pop-ups These are pop-ups that appear as a separate browser window. Web pop-ups    
JS Alerts These alerts are native browser pop-ups and are classified as an alert, a confirm alert, or a prompt alert. Check out Selenium documentation to learn more about these alerts. JS alerts    
Permission pop-ups These alerts are raised by some applications that might need permission to access native device features, such as camera or microphone. Permission pop-ups    
Location pop-ups These alerts are raised by applications that want to show their customers region-specific offers, currency, or other information. Location pop-ups    
Notification pop-ups These alerts are raised by applications for permission to push notifications to the foreground of the user’s screen. Notification pop-ups    

In this guide, you will also learn how to:

Web pop-ups

The web pop-ups appear as a separate window when accessing a website as shown in the following image. Apart from closing the pop-up, sometimes, these pop-ups require you to click a button as acceptance optionally. These workflows are mostly related to advertising, subscription, opt-in, etc. You can handle such pop-ups, as explained in this section.

Browser Location Access Popup

The default pop-up behavior in different browsers on desktop devices is as follows:

Browser Pop-ups enabled by default      
Chrome Yes      
Safari No      
Edge Yes      
Firefox Yes      
Note: You can handle most pop-ups that appear in mobile devices using NATIVE_APP context. Check out how to handle pop-ups in native context to learn about managing web pop-ups in mobile devices.

Enable all pop-ups in Safari or IE for desktop devices

To test if the pop-ups appear in Safari or IE, you can enable pop-ups as follows:

To enable the pop-ups in IE, use the browserstack.ie.enablePopups capability.

caps.setCapability("browserstack.ie.enablePopups", "true");
caps["browserstack.ie.enablePopups"] = "true"
desiredCap.SetCapability("browserstack.ie.enablePopups", "true");
caps["browserstack.ie.enablePopups"] = "true"
var capabilities = {
  "browserstack.ie.enablePopups" : "true"
}
$caps["browserstack.ie.enablePopups"] = "true";
$caps->{"browserstack.ie.enablePopups"} = "true";

To enable the popups in Safari, use the browserstack.safari.enablePopups capability.

caps.setCapability("browserstack.safari.enablePopups", "true");
caps["browserstack.safari.enablePopups"] = "true"
desiredCap.SetCapability("browserstack.safari.enablePopups", "true");
caps["browserstack.safari.enablePopups"] = "true"
var capabilities = {
  "browserstack.safari.enablePopups" : "true"
}
$caps["browserstack.safari.enablePopups"] = "true";
$caps->{"browserstack.safari.enablePopups"} = "true";

Disable all pop-ups in Chrome, Firefox, and Edge for desktop devices

Use the sample code snippets to disable pop-ups in the following browsers.

ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
caps.setCapability(ChromeOptions.CAPABILITY, options);
caps = Selenium::WebDriver::Remote::Capabilities.chrome
caps["chromeOptions"] = {}
caps["chromeOptions"]["excludeSwitches"] = ["disable-popup-blocking"]
using OpenQA.Selenium.Chrome;

ChromeOptions options = new ChromeOptions();
options.AddExcludedArgument("disable-popup-blocking");
desired_cap = {
 'browser': 'chrome',
 'browser_version': 'latest',
 'os': 'Windows',
 'os_version': '10',
 'build': 'Python Sample Build',
 'name': 'Pop-ups testing'
}
desired_cap["chromeOptions"] = {}
desired_cap["chromeOptions"]["excludeSwitches"] = ["disable-popup-blocking"]

driver = webdriver.Remote(
    command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub',
    desired_capabilities=desired_cap
    )
# Rest of the code goes here
const webdriver = require('selenium-webdriver');

// Input capabilities
const capabilities = {
  //To test on mobiles devices, use these capabilities.
  // 'browserName': 'Safari',
  // 'os_version': '14',
  // 'device': 'iPhone 12',
  // 'real_mobile': 'true',
  'browserName': 'Chrome',
  'os': 'Windows',
  'os_version': '7',
  'build': 'Pop-ups in Browsers ',
  'name': 'popups disabled in chrome',
  'browserstack.user' : 'YOUR_USERNAME',
  'browserstack.key' : 'YOUR_ACCESS_KEY',
   "chromeOptions" : {
    "excludeSwitches" : ["disable-popup-blocking"],
    "args" : ["incognito"]
  }
}

async function runSampleTest () {
  let driver;
  try {
    driver = new webdriver.Builder().
      usingServer('http://hub-cloud.browserstack.com/wd/hub').
      withCapabilities(capabilities).build();
    await driver.get('https://www.webroot.com/services/popuptester1.htm');
    const title = await driver.getTitle();
    console.log(title);
  } catch (e) {
    console.log(e);
  } finally {
    if(driver) {
      await driver.quit();
    }
  }
}
runSampleTest();
$chromeoptions = array("excludeSwitches"=>array("disable-popup-blocking"));
$caps = array("platform"=>"WINDOWS", "browserName"=>"chrome", "chromeOptions"=>$chromeoptions);
$caps->{"chromeOptions"} = { "excludeSwitches" => ("disable-popup-blocking") };
const webdriver = require('selenium-webdriver');

// Input capabilities
const capabilities = {
  'browserName': 'Edge',
  'os': 'Windows',
  'os_version': '7',
  'build': 'Pop-ups in Browsers ',
  'name': 'popups disabled in Edge',
  'browserstack.user' : 'YOUR_USERNAME',
  'browserstack.key' : 'YOUR_ACCESS_KEY',
   "edgeOptions" : {
    "excludeSwitches" : ["disable-popup-blocking"],
    "args" : ["incognito"]
  }
}

async function runSampleTest () {
  let driver;
  try {
    driver = new webdriver.Builder().
      usingServer('http://hub-cloud.browserstack.com/wd/hub').
      withCapabilities(capabilities).build();
    await driver.get('https://www.webroot.com/services/popuptester1.htm');
    const title = await driver.getTitle();
    console.log(title);
  } catch (e) {
    console.log(e);
  } finally {
    if(driver) {
      await driver.quit();
    }
  }
}
runSampleTest();
const webdriver = require('selenium-webdriver');

// Input capabilities
const capabilities = {
  'browserName': 'Firefox',
  'os': 'Windows',
  'os_version': '7',
  'build': 'Pop-ups in Browsers ',
  'name': 'pop-ups disabled in Firefox',
  'browserstack.user' : 'YOUR_USERNAME',
  'browserstack.key' : 'YOUR_ACCESS_KEY',
  'moz:firefoxOptions': {
        prefs: {
          'dom.disable_beforeunload': true,
          'dom.disable_open_during_load': true,
        }
    }
}
async function runSampleTest () {
  let driver;
  try {
    driver = new webdriver.Builder().
      usingServer('http://hub-cloud.browserstack.com/wd/hub').
      withCapabilities(capabilities).build();
    await driver.get('https://www.webroot.com/services/popuptester1.htm');
    const title = await driver.getTitle();
    console.log(title);
  } catch (e) {
    console.log(e);
  } finally {
    if(driver) {
      await driver.quit();
    }
  }
}
runSampleTest();

Know your location pop-up

Use the sample code snippets to disable the know your location pop-up in the following devices.

If your web application requests access to your location, the following pop-up appears on the desktop where the test is running:

Browser Location Access Popup

The snippet below lets you automate an Allow or Block interaction when the remote browser requests the location.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class AllowGeoLocationPopup {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Chrome");
    caps.setCapability("browser_version", "75.0");
    caps.setCapability("os", "Windows");
    caps.setCapability("os_version", "10");

    // INIT CHROME OPTIONS
    ChromeOptions options = new ChromeOptions();
    Map < String, Object > prefs = new HashMap < String, Object > ();
    Map < String, Object > profile = new HashMap < String, Object > ();
    Map < String, Object > contentSettings = new HashMap < String, Object > ();

    // SET CHROME OPTIONS
    // 0 - Default, 1 - Allow, 2 - Block
    contentSettings.put("geolocation", 1);
    profile.put("managed_default_content_settings", contentSettings);
    prefs.put("profile", profile);
    options.setExperimentalOption("prefs", prefs);

    // SET CAPABILITY
    caps.setCapability(ChromeOptions.CAPABILITY, options);
    WebDriver driver = new RemoteWebDriver(new URL(URL), caps);
    driver.get("https://the-internet.herokuapp.com/geolocation");
    driver.findElement(By.xpath("//*[@id='content']/div/button")).click();
    Thread.sleep(5000);
    driver.quit();
  }
}
let webdriver = require('wd');

// SET CAPABILITY
let capabilities = {
  'browserName' : 'Chrome',
  'browser_version' : '95',
  'os' : 'Windows',
  'os_version' : '10',
  'browserstack.user' : 'YOUR_USERNAME',
  'browserstack.key' : 'YOUR_ACCESS_KEY',
  'build': 'Location pop-ups in Browsers ',
  'name': 'location popups disabled in Chrome',
  'goog:chromeOptions': {
      prefs: {
       // 0 - Default, 1 - Allow, 2 - Block
        'profile.managed_default_content_settings.geolocation' : 1
    }
 }
//  // SET Firefox options
//   'moz:firefoxOptions': {
//         prefs: {
//           'dom.disable_beforeunload': true,
//           'dom.webnotifications.enabled': false,
//           'geo.enabled': true,
//           'geo.provider.use_corelocation': false,
//           'geo.prompt.testing': true,
//           'geo.prompt.testing.allow': true,
//         }
//   }
//  // SET Edge options
// 'ms:edgeOptions': {
//       prefs: {
//        // 0 - Default, 1 - Allow, 2 - Block
//         'profile.managed_default_content_settings.geolocation' : 1
//     }
//  }
}

let driver = webdriver.promiseRemote("http://hub-cloud.browserstack.com/wd/hub");
driver.init(capabilities, function() {
  driver.get('https://the-internet.herokuapp.com/geolocation')
    .then(function() {
      (async () => {
        let element = await driver.element("xpath", "//button[contains(text(),'Where am I?')]");
        await element.click();
        await driver.quit();
      })();
    });
});
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;

namespace SampleCSharp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            RemoteWebDriver driver;
            Dictionary<string, object> profile = new Dictionary<string, object>();

            // 0 - Default, 1 - Allow, 2 - Block
            profile.Add("profile.default_content_setting_values.geolocation", 1);

            // INIT OPTIONS
            Dictionary<string, object> chromeOptions = new Dictionary<string, object>();
            //Set edgeOptions
            // Dictionary<string, object> edgeOptions = new Dictionary<string, object>();

            // SET CHROME OPTIONS
            chromeOptions.Add("prefs", profile);
            // SET EDGE OPTIONS
            // edgeOptions.Add("prefs", profile);

            // SET CAPABILITY
            ChromeOptions capability = new ChromeOptions();
            capability.AddAdditionalCapability("browser", "Chrome", true);
            //Set Edge capabilities
            // EdgeOptions capability = new EdgeOptions();
            // capability.AddAdditionalCapability("browser", "Edge", true);
            capability.AddAdditionalCapability("browser_version", "75.0", true);
            capability.AddAdditionalCapability("os", "Windows", true);
            capability.AddAdditionalCapability("os_version", "10", true);
            capability.AddAdditionalCapability("browserstack.debug", "true", true);
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);
            capability.AddAdditionalCapability("chromeOptions", chromeOptions, true);
            //Set edgeOptions 
            // capability.AddAdditionalCapability("edgeOptions", edgeOptions, true);

            driver = new RemoteWebDriver(new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability);
            driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/geolocation");
            driver.FindElement(By.XPath("//*[@id='content']/div/button")).Click();
            Thread.Sleep(5000);
            driver.Quit();
        }

    }
}

from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options

# INIT OPTIONS
# Initialize chromeoptions
chrome_options = Options()

# Intialize edgeoptions
edge_options = Options()
# 0 - Default, 1 - Allow, 2 - Block
# edge_options.add_experimental_option("prefs", { "profile.default_content_setting_values.geolocation": 1})
# Initialize firefoxoptions
# firefox_options = Options()


# SET OPTIONS
# Set chromeOptions
# 0 - Default, 1 - Allow, 2 - Block
chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.geolocation": 1})
# Set firefoxOptions
# firefox_options.add_experimental_option("prefs", 
# { "dom.disable_beforeunload": True, 
#   'dom.webnotifications.enabled': False, 
#   'geo.enabled': True,
#   'geo.provider.use_corelocation': False,
#   'geo.prompt.testing': True,
#   'geo.prompt.testing.allow': True,})
# Set edgeOptions
# 0 - Default, 1 - Allow, 2 - Block
# edge_options.add_experimental_option("prefs", { "profile.default_content_setting_values.geolocation": 1})


# SET CAPABILITY
# Change desired cap to "edge_options" for Edge and "firefox_options" for Firefox
desired_cap = chrome_options.to_capabilities()
desired_cap.update({
  'browser_version': '95',
  "browser": 'Chrome',
  'os': 'Windows',
  'os_version': '10'
})

driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://the-internet.herokuapp.com/geolocation")
driver.find_element_by_xpath("//*[@id='content']/div/button").click()
sleep(10)
driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# SET OPTIONS
# Set chromeOptions
# 0 - Default, 1 - Allow, 2 - Block
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"prefs" => { "profile.default_content_setting_values.geolocation" => 1 } })
# Set edgeOptions
# caps = Selenium::WebDriver::Remote::Capabilities.edge("edgeOptions" => {"prefs" => { "profile.default_content_setting_values.geolocation" => 1 } })
  

# SET CAPABILITY
caps['browser'] = 'Chrome'
caps['browser_version'] = '95.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
driver = Selenium::WebDriver.for(:remote,
  :url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
  :desired_capabilities => caps)
driver.navigate.to "https://the-internet.herokuapp.com/geolocation"
driver.find_element(:xpath, "//*[@id='content']/div/button").click;
sleep 2
driver.quit

When a web application requests access to the location, the following pop-ups appear mobile device where the test is running:

Mobile Device Location Access Popup

The following snippet lets you automate an Allow or Block interaction when the remote browser requests a mobile device for location.

import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;

import java.net.URL;
import java.util.Set;

public class AllowGeoLocationPopup {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Chrome");
    caps.setCapability("browserName", "android");
    caps.setCapability("device", "Samsung Galaxy S10");
    caps.setCapability("realMobile", "true");
    caps.setCapability("os_version", "9.0");
    AppiumDriver driver = new AndroidDriver(new URL(URL), caps);
    driver.get("https://the-internet.herokuapp.com/geolocation");
    driver.findElement(By.xpath("//*[@id='content']/div/button")).click();
    Thread.sleep(5000);
    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    driver.context("NATIVE_APP");
    driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
    Thread.sleep(5000);
    driver.quit();
  }
}
let webdriver = require('wd');

// SET CAPABILITY
let capabilities = {
  'os_version': '11.0',
  'device': 'Samsung Galaxy S21',
  'real_mobile': 'true',
  'browserstack.user' : 'YOUR_USERNAME',
  'browserstack.key' : 'YOUR_ACCESS_KEY',
  'build': 'Location pop-ups in Browsers ',
  'name': 'location popups disabled in Chrome',
  'goog:chromeOptions': {
      prefs: {
       // 0 - Default, 1 - Allow, 2 - Block
        'profile.managed_default_content_settings.geolocation' : 1
    }
 }
}

let driver = webdriver.promiseRemote("http://hub-cloud.browserstack.com/wd/hub");
driver.init(capabilities, function() {
  driver.get('https://the-internet.herokuapp.com/geolocation')
    .then(function() {
      (async () => {
        let element = await driver.element("xpath", "//button[contains(text(),'Where am I?')]");
        await element.click();
        //To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
        await driver.context('NATIVE_APP');
        //Set text to "Block" to block the permission.
        let element2 = await driver.element("xpath", ".//android.widget.Button[@text='Allow']")
        await element2.click();
        await driver.quit();
      })();
    });
});
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using System.Collections.Generic;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Appium.iOS;

namespace SampleCSharp
{
    class Program
    {
        public static void Main(string[] args)
        {
            AppiumOptions capability = new AppiumOptions();

            capability.AddAdditionalCapability("device", "Samsung Galaxy S8");
            capability.AddAdditionalCapability("os_version", "7.0");
            capability.AddAdditionalCapability("real_mobile", "true");
            capability.AddAdditionalCapability("browserstack.debug", "true");
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
            AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(new Uri("http://hub-cloud.browserstack.com/wd/hub"), capability);
            driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/geolocation");
            Thread.Sleep(5000);
            IWebElement ll = driver.FindElement(By.XPath("//*[@id='content']/div/button"));
            ll.Click();
            Thread.Sleep(5000);
            // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
            driver.Context = ("NATIVE_APP");
            ll = driver.FindElement(By.XPath(".//android.widget.Button[@text='Allow']"));
            ll.Click();
            driver.Quit();
        }
    }
}
import time
from appium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
  'device': 'Samsung Galaxy S10',
  'realMobile': 'true',
  'os_version': '9.0'
}
driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://the-internet.herokuapp.com/geolocation")
driver.find_element_by_xpath("//*[@id='content']/div/button").click()
time.sleep(2)
# To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
time.sleep(2)
driver.quit()
require 'rubygems'
require 'appium_lib'

caps = {}
caps['device'] = 'Samsung Galaxy S10'
caps['platformName'] = 'Android'
caps['realMobile'] = 'true'
caps['os_version'] = '9.0'
appium_driver = Appium::Driver.new({
  'caps' => caps,
  'appium_lib' => {
      :server_url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"
  }}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://the-internet.herokuapp.com/geolocation"
driver.find_element(:xpath, "//*[@id='content']/div/button").click;
sleep(2)
# To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
driver.set_context('NATIVE_APP')
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
sleep(2)
driver.quit
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import java.net.URL;
import java.util.Set;

public class AllowGeoLocationPopup {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("os_version", "14");
    caps.setCapability("device", "iPhone 12");
    caps.setCapability("realMobile", "true");    

    IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub"), caps);
    driver.get("https://the-internet.herokuapp.com/geolocation");
    driver.findElement(By.xpath("//*[@id='content']/div/button")).click();
    Thread.sleep(5000);
    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    driver.context("NATIVE_APP");
    driver.findElement(By.name("Allow")).click();
    Thread.sleep(5000);
    driver.quit();
  }
}
let webdriver = require('wd');

// SET CAPABILITY
let capabilities = {
// // To test on mobile devices, use these capabilities.
  'os_version': '14',
  'device': 'iPhone 12',
  'real_mobile': 'true',
  'browserstack.user' : 'YOUR_USERNAME',
  'browserstack.key' : 'YOUR_ACCESS_KEY',
  'build': 'Location pop-ups in Browsers ',
  'name': 'location popups disabled',
  'autoAcceptPermissions': 'True',
  'autoAcceptAlerts': 'True',
}

let driver = webdriver.promiseRemote("http://hub-cloud.browserstack.com/wd/hub");
driver.init(capabilities, function() {
  driver.get('https://the-internet.herokuapp.com/geolocation')
    .then(function() {
      (async () => {
        let element = await driver.element("xpath", "//button[contains(text(),'Where am I?')]");
        await element.click();
        await driver.quit();
      })();
    });
});
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using System.Collections.Generic;
using OpenQA.Selenium.Appium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Appium.iOS;

namespace SampleCSharp
{
    class Program
    {
        public static void Main(string[] args)
        {
            AppiumOptions capability = new AppiumOptions();

            capability.AddAdditionalCapability("device", "iPhone 12");
            capability.AddAdditionalCapability("os_version", "14");
            capability.AddAdditionalCapability("real_mobile", "true");
            capability.AddAdditionalCapability("browserstack.debug", "true");
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
            IOSDriver<IWebElement>  driver = new IOSDriver<IWebElement>(
              new Uri("https://u:p@hub-cloud.browserstack.com/wd/hub/"), capability
            );
            driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/geolocation");
            Thread.Sleep(5000);
            IWebElement ll = driver.FindElement(By.XPath("//*[@id='content']/div/button"));
            ll.Click();
            Thread.Sleep(5000);
            // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
            driver.Context = ("NATIVE_APP");
            ll = driver.FindElement(By.Name("Allow"));
            ll.Click();
            driver.Quit();
        }
    }
}
import time
from appium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
  "os_version" : "14",
  "device" : "iPhone 12",
  "real_mobile" : "true",
}
driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://the-internet.herokuapp.com/geolocation")
driver.find_element_by_xpath("//*[@id='content']/div/button").click()
time.sleep(2)
# To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name('Allow').click()
time.sleep(2)
driver.quit()
require 'rubygems'
require 'appium_lib'

caps = {}
caps['device'] = 'iPhone 12'
caps['platformName'] = 'iOS'
caps['realMobile'] = 'true'
caps['os_version'] = '14'

appium_driver = Appium::Driver.new({
  'caps' => caps,
  'appium_lib' => {
      :server_url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"
  }}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://the-internet.herokuapp.com/geolocation"
driver.find_element(:xpath, "//*[@id='content']/div/button").click;
sleep(2)
# To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
driver.set_context('NATIVE_APP')
driver.find_element(:name, "Allow").click;
sleep(2)
driver.quit

Camera and microphone pop-ups

Use the sample code snippets to disable the camera and microphone pop-ups on the following devices.

When a web application requires access to the camera and microphone, the following pop-ups appear on the desktop:

use camera android Microphone Permission popup

The snippet below lets you automate an Allow or Block interaction when your web app requests access to a camera or microphone.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;

public class AllowCameraPopupChrome {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {

    //Configure ChromeOptions to pass fake media stream
    ChromeOptions options = new ChromeOptions();
    options.addArguments("use-fake-device-for-media-stream");
    options.addArguments("use-fake-ui-for-media-stream");

    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Chrome");
    caps.setCapability("browser_version", "75.0");
    caps.setCapability("os", "Windows");
    caps.setCapability("os_version", "10");
    caps.setCapability(ChromeOptions.CAPABILITY, options);
    WebDriver driver = new RemoteWebDriver(new URL(URL), caps);

    //WebCam Test
    driver.get("https://webcamtests.com/check");
    Thread.sleep(5000);
    driver.findElement(By.id("webcam-launcher")).click();
    Thread.sleep(2000);

    //Mic Test
    driver.get("https://www.vidyard.com/mic-test/");
    Thread.sleep(2000);
    driver.findElement(By.xpath("//a[@id='start-test']")).click();
    Thread.sleep(2000);

    driver.quit();
  }
}
var webdriver = require('selenium-webdriver');
var chrome = require("selenium-webdriver/chrome");
const {By} = require('selenium-webdriver');

var capabilities = {
  'browserName': 'Chrome',
  'browser_version': '95.0',
  'os': 'Windows',
  'os_version': '10',
  'build': 'new camera/mic popup tests',
  'safariAllowPopups': 'true',
  'autoAcceptPermissions': 'true',
  'autoAcceptAlerts': 'True',
  // Configure ChromeOptions to pass fake media stream
  'goog:chromeOptions': {
    'args': ["--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream"]
  }
// // Configure edgeOptions to pass fake media stream
//   'ms:edgeOptions': {
//       'args': ["--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream"]
//  }
// // Configure firefoxOptions to pass fake media stream
// 'moz:firefoxOptions': {
//       prefs: {
//         'dom.disable_beforeunload': true,
//         'dom.webnotifications.enabled': false,
//         'media.webrtc.hw.h264.enabled': true,
//         'media.getusermedia.screensharing.enabled': true,
//         'media.navigator.permission.disabled': true,
//         'media.navigator.streams.fake': true,
//         'media.peerconnection.video.h264_enabled': true,
//       }
//   }
}

async function runTestWithCaps () {
  let driver = new webdriver.Builder().usingServer('http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();
  await driver.get("https://webcamtests.com/check");
  var x = await driver.wait(webdriver.until.elementIsVisible(driver.findElement(By.xpath('//*[@id="webcam-launcher"]'), 1000)));
  await x.click()
  await driver.get("https://www.vidyard.com/mic-test/");
  var elements = await driver.wait(driver.findElements(By.css('#gdpr-banner > div > button'), 1000));
  if (elements.length > 0){
    await elements[0].click()
  }
  y = await driver.wait(webdriver.until.elementIsVisible(driver.findElement(By.xpath('//*[@id="start-test"]'), 1000)));   
//   await sleep(5000);
  await y.click() 
  await driver.quit();
}
runTestWithCaps(); 
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using OpenQA.Selenium.Chrome;

namespace SampleCSharp
{
    public class AllowCameraMicPopupChrome
    {
        static void Main(string[] args)
        {
            IWebDriver driver;

            //Configure ChromeOptions to pass fake media stream
            ChromeOptions chromeOptions = new ChromeOptions();
            chromeOptions.AddArgument("--use-fake-device-for-media-stream");
            chromeOptions.AddArgument("--use-fake-ui-for-media-stream");

            chromeOptions.AddAdditionalCapability("browser", "Chrome", true);
            chromeOptions.AddAdditionalCapability("browser_version", "70.0", true);
            chromeOptions.AddAdditionalCapability("os", "Windows", true);
            chromeOptions.AddAdditionalCapability("os_version", "10", true);
            chromeOptions.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
            chromeOptions.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);

            driver = new RemoteWebDriver(
              new Uri("http://hub-cloud.browserstack.com/wd/hub/"), chromeOptions);

            // Webcam Test           
            driver.Navigate().GoToUrl("https://webcamtests.com/check");
            Thread.Sleep(5000);
            driver.FindElement(By.Id("webcam-launcher")).Click();
            Thread.Sleep(5000);

            // Mic Test
            driver.Navigate().GoToUrl("https://www.vidyard.com/mic-test/");
            Thread.Sleep(2000);
            driver.FindElement(By.XPath("//a[@id='start-test']")).Click();
            Thread.Sleep(5000);

            driver.Quit();
        }
    }
}
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
import time

desired_cap = {
  'browser_version': '75.0',
  'os': 'Windows',
  'os_version': '10',

  #Configure ChromeOptions to pass fake media stream
  'chromeOptions': {
    'args': ["--use-fake-device-for-media-stream", "--use-fake-ui-for-media-stream"]
  }
}
driver = webdriver.Remote(command_executor = 'http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities = desired_cap)

# WebCam Test
driver.get("https://webcamtests.com/check")
time.sleep(5)
driver.find_element_by_id("webcam-launcher").click()
time.sleep(5)

# Mic Test
driver.get("https://www.vidyard.com/mic-test/")
time.sleep(5)
driver.find_element_by_xpath("//a[@id='start-test']").click()
time.sleep(10)
driver.quit()
require 'rubygems'
require 'selenium-webdriver'

#Configure ChromeOptions to pass fake media stream
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"args" => ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'] })
caps['browser'] = 'Chrome'
caps['browser_version'] = '75.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
driver = Selenium::WebDriver.for(:remote, :url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub", :desired_capabilities => caps)

# WebCam Test
driver.navigate.to "https://webcamtests.com/check"
sleep(5)
driver.find_element(:id, "webcam-launcher").click;
sleep(5)

#Mic Test
driver.navigate.to "https://www.vidyard.com/mic-test/"
sleep(5)
driver.find_element(:xpath, "//a[@id='start-test']").click;
sleep(10)
driver.quit

When a web application requests access to the camera and microphone, the following pop-ups apear in the mobile device:

Android Use Your Camera Permission Popup Microphone Permission popup

The snippet below lets you automate an Allow or Block interaction on mobile devices when the remote browser requests for access to the camera or microphone.

import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;

import java.net.URL;

public class AllowCameraPopupChromeMobile {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Chrome");
    caps.setCapability("device", "Samsung Galaxy S10");
    caps.setCapability("realMobile", "true");
    caps.setCapability("os_version", "9.0");
    AppiumDriver driver = new AndroidDriver(new URL(URL), caps);

    //WebCam Test
    driver.get("https://webcamtests.com/check");
    Thread.sleep(2000);
    driver.findElement(By.id("webcam-launcher")).click();
    Thread.sleep(2000);
    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    driver.context("NATIVE_APP");
    driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
    driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
    Thread.sleep(5000);

    driver.context("CHROMIUM");

    //Mic Test
    driver.get("https://www.vidyard.com/mic-test/");
    Thread.sleep(2000);
    driver.findElement(By.xpath("//a[@id='start-test']")).click();
    Thread.sleep(2000);
    driver.context("NATIVE_APP");
    driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
    driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
    Thread.sleep(2000);

    driver.quit();
  }
}
let webdriver = require('wd');

let capabilities = {
  'os_version': '9.0',
  'device': 'Samsung Galaxy S10',
  'real_mobile': 'true',
  'browserstack.user': 'YOUR_USERNAME',
  'browserstack.key': 'YOUR_ACCESS_KEY'
}

const sleep = require('util').promisify(setTimeout)
let driver = webdriver.promiseRemote("http://hub-cloud.browserstack.com/wd/hub");
driver.init(capabilities, function() {
  (async () => {
    // Camera Test
    await driver.get('https://webcamtests.com/check');
    await sleep(3000);
    let element = await driver.element("id", "webcam-launcher");
    await element.click();

    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    await driver.context('NATIVE_APP');
    let element2 = await driver.element("xpath", ".//android.widget.Button[@text='Allow']")
    await element2.click();
    await sleep(5000);

    await driver.context('CHROMIUM');

    // Mic Test
    await driver.get('https://www.vidyard.com/mic-test/');
    await sleep(3000);
    let element4 = await driver.element("xpath", "//a[@id='start-test']");
    await element4.click();
    await driver.context('NATIVE_APP');
    let element5 = await driver.element("xpath", ".//android.widget.Button[@text='Allow']")
    await element5.click();
    let element6 = await driver.element("xpath", ".//android.widget.Button[@text='Allow']")
    await element6.click();
    await sleep(3000);
    await driver.quit();
  })();
});
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium;

namespace SampleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {

            AppiumOptions capability = new AppiumOptions();

            capability.AddAdditionalCapability("device", "Samsung Galaxy S10");
            capability.AddAdditionalCapability("os_version", "9.0");
            capability.AddAdditionalCapability("real_mobile", "true");
            capability.AddAdditionalCapability("browserstack.debug", "true");
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
            AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(new Uri("http://hub-cloud.browserstack.com/wd/hub"), capability);

            // Camera Test
            driver.Navigate().GoToUrl("https://webcamtests.com/check");
            Thread.Sleep(2000);
             driver.FindElement(By.Id("webcam-launcher")).Click();
            // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
            driver.Context = ("NATIVE_APP");
            driver.FindElement(By.XPath(".//android.widget.Button[@text='Allow']")).Click();
            driver.FindElement(By.XPath(".//android.widget.Button[@text='Allow']")).Click();

            Thread.Sleep(5000);

            driver.Context = ("CHROMIUM");

            // Mic Test
            driver.Navigate().GoToUrl("https://www.vidyard.com/mic-test/");
            Thread.Sleep(2000);
            driver.FindElement(By.XPath("//a[@id='start-test']")).Click();
            driver.Context = ("NATIVE_APP");
            driver.FindElement(By.XPath(".//android.widget.Button[@text='Allow']")).Click();
            driver.FindElement(By.XPath(".//android.widget.Button[@text='Allow']")).Click();
            Thread.Sleep(2000);
            driver.Quit();
        }
    }
}
import time
from appium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
  'device': 'Samsung Galaxy S10',
  'realMobile': 'true',
  'os_version': '9.0'
}
driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities=desired_cap)

# Camera Test
driver.get("https://webcamtests.com/check")
time.sleep(2)
driver.find_element_by_id("webcam-launcher").click()
# To accept/block the popup, you need to switch the context to NATIVE_APP and click on the Allow/Block button.
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
time.sleep(5)

driver.switch_to.context('CHROMIUM')

# Mic Test
driver.get("https://www.vidyard.com/mic-test/")
time.sleep(2)
driver.find_element_by_xpath("//a[@id='start-test']").click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
time.sleep(2)
driver.quit()
require 'rubygems'
require 'appium_lib'

caps = {}
caps['device'] = 'Samsung Galaxy S10'
caps['platformName'] = 'Android'
caps['realMobile'] = 'true'
caps['os_version'] = '9.0'
appium_driver = Appium::Driver.new({'caps' => caps,'appium_lib' => { :server_url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub" }}, true)
driver = appium_driver.start_driver

# WebCam Test
driver.navigate.to "https://webcamtests.com/check"
sleep(2)
driver.find_element(:id, "webcam-launcher").click;
# To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
driver.set_context('NATIVE_APP')
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
sleep(5)

driver.set_context('CHROMIUM')

# Mic Test
driver.navigate.to "https://www.vidyard.com/mic-test/"
sleep(2)
driver.find_element(:xpath, "//a[@id='start-test']").click;
driver.set_context('NATIVE_APP')
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
sleep(2)
driver.quit
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.ios.IOSDriver;
import io.appium.java_client.ios.IOSElement;
import java.net.URL;
import java.util.Set;

public class camera {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("device", "iPhone 12");
    caps.setCapability("realMobile", "true");
    caps.setCapability("os_version", "14.0");
    caps.setCapability("device", "iPhone 12");
    caps.setCapability("nativeWebTap", "true");
    IOSDriver<IOSElement> driver = new IOSDriver<IOSElement>(new URL("https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub"), caps);

  //WebCam Test
    driver.get("https://webcammictest.com/");
    Thread.sleep(2000);
    driver.findElement(By.xpath("//button[contains(text(),'Test webcam')]")).click();
    Thread.sleep(2000);
    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    driver.context("NATIVE_APP");
    WebElement ele = driver.findElement(By.id("Allow"));
    ele.click();
    Thread.sleep(5000);
    Set<String> contextNames = driver.getContextHandles();
    driver.context(contextNames.toArray()[1].toString());

    //Mic Test
    driver.get("https://www.vidyard.com/mic-test/");
    Thread.sleep(2000);
    driver.findElement(By.xpath("//a[@id='start-test']")).click();
    Thread.sleep(2000);
    driver.context("NATIVE_APP");
    driver.findElement(By.name("Allow")).click();
    Thread.sleep(2000);
    driver.quit();
  }
}
let webdriver = require('wd');

let capabilities = {
  'os_version': '14',
  'device': 'iPhone12',
  'real_mobile': 'true',
  'browserstack.user': 'YOUR_USERNAME',
  'browserstack.key': 'YOUR_ACCESS_KEY'
}

const sleep = require('util').promisify(setTimeout)
let driver = webdriver.promiseRemote("http://hub-cloud.browserstack.com/wd/hub");
driver.init(capabilities, function() {
  (async () => {
    // Camera Test
    await driver.get('https://webcammictest.com/');
    await sleep(3000);
    let element2 = await driver.element("xpath", "//button[contains(text(),'Test webcam')]")
    await element2.click();
    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    await driver.context('NATIVE_APP');
    let element3 = await driver.element("name", "Allow")
    await element3.click();
    await sleep(5000);
    let contexts = await driver.contexts();
    await driver.context(contexts[1]);

    // Mic Test
    await driver.get('https://www.vidyard.com/mic-test/');
    await sleep(3000);
    let element4 = await driver.element("xpath", "//a[@id='start-test']");
    await element4.click();
    await sleep(3000);
    await driver.context('NATIVE_APP');
    let element5 = await driver.element("name", "Allow")
    await element5.click();
    await driver.quit();
  })();
});

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using OpenQA.Selenium.Appium.iOS;
using OpenQA.Selenium.Appium;

namespace SampleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            AppiumOptions capability = new AppiumOptions();

            capability.AddAdditionalCapability("device", "iPhone 12");
            capability.AddAdditionalCapability("os_version", "14");
            capability.AddAdditionalCapability("real_mobile", "true");
            capability.AddAdditionalCapability("browserstack.debug", "true");

            IOSDriver<IWebElement> driver = new IOSDriver<IWebElement>(new Uri("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub/"), capability);

            driver.Navigate().GoToUrl("https://webcammictest.com/");
            Thread.Sleep(2000);
            driver.FindElement(By.XPath("//button[contains(text(),'Test webcam')]")).Click();
            Thread.Sleep(2000);
            driver.Context = ("NATIVE_APP");
            IWebElement ele = driver.FindElement(By.Id("Allow"));
            ele.Click();
            driver.Context = driver.Contexts[1];
            Thread.Sleep(2000);

            driver.Navigate().GoToUrl("https://www.vidyard.com/mic-test/");
            IWebElement ll = driver.FindElement(By.XPath("//a[@id='start-test']"));
            ll.Click();
            Thread.Sleep(2000);
            // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
            driver.Context = ("NATIVE_APP");
            ll = driver.FindElement(By.Name("Allow"));
            ll.Click();
            Thread.Sleep(5000);
            driver.Quit();
        }
    }
}
import time
from appium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
  'device': 'iPhone12',
  'realMobile': 'true',
  'os_version': '14'
}
driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://webcammictest.com/")
time.sleep(5)
driver.find_element_by_xpath("//button[contains(text(),'Test webcam')]").click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name("Allow").click()
driver.switch_to.context(driver.contexts[1])
driver.get("https://www.vidyard.com/mic-test/")
driver.find_element_by_xpath("//a[@id='start-test']").click()
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_name("Allow").click()
driver.quit()
require 'rubygems'
require 'appium_lib'

caps = {}
caps['device'] = 'iPhone12'
caps['realMobile'] = 'true'
caps['os_version'] = '14.0'
caps['platformName'] = 'iOS'
appium_driver = Appium::Driver.new({'caps' => caps,'appium_lib' => { :server_url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub" }}, true)
driver = appium_driver.start_driver

# WebCam Test
driver.navigate.to "https://webcammictest.com/"
sleep(2)
driver.find_element(:xpath, "//button[contains(text(),'Test webcam')]").click;
driver.set_context('NATIVE_APP')
driver.find_element(:name, "Allow").click;
contexts = driver.available_contexts
driver.set_context contexts[1]
sleep(2)
# Mic Test
driver.navigate.to "https://www.vidyard.com/mic-test/"
sleep(2)
driver.find_element(:xpath, "//a[@id='start-test']").click;
driver.set_context('NATIVE_APP')
driver.find_element(:name, "Allow").click;
sleep(2)
driver.quit

Show notifications pop-ups

Use the sample code snippets to disable the notification pop-up in the following devices.

When your web application requests permission to show notifications, the following pop-up appears on desktop devices:

popup for notification permission

The snippet below lets you automate an Allow or Block interaction when your web app requests permission to show notifications.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class AllowNotificationPopupDesktop {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Chrome");
    caps.setCapability("browser_version", "75.0");
    caps.setCapability("os", "Windows");
    caps.setCapability("os_version", "10");

    // INIT CHROME OPTIONS
    ChromeOptions options = new ChromeOptions();
    Map<String, Object> prefs = new HashMap<String, Object>();
    Map<String, Object> profile = new HashMap<String, Object>();
    Map<String, Object> contentSettings = new HashMap<String, Object>();

    // SET CHROME OPTIONS
    // 0 - Default, 1 - Allow, 2 - Block
    contentSettings.put("notifications", 1);
    profile.put("managed_default_content_settings", contentSettings);
    prefs.put("profile", profile);
    options.setExperimentalOption("prefs", prefs);

    // SET CAPABILITY
    caps.setCapability(ChromeOptions.CAPABILITY, options);

    WebDriver driver = new RemoteWebDriver(new URL(URL), caps);

    driver.get("https://web-push-book.gauntface.com/demos/notification-examples/");
    driver.findElement(By.xpath("//body/main[1]/p[3]/input[1]")).click();
    Thread.sleep(2000);
    driver.quit();
  }
}
var webdriver = require('selenium-webdriver');
var chrome = require("selenium-webdriver/chrome");

var capabilities = {
  'browserName': 'Chrome',
  'browser_version': '75.0',
  'os': 'Windows',
  'os_version': '10',
  'browserstack.user': 'YOUR_USERNAME',
  'browserstack.key': 'YOUR_ACCESS_KEY',
  'goog:chromeOptions': {
    prefs: {
      // 0 - Default, 1 - Allow, 2 - Block
      'profile.managed_default_content_settings.notifications': 1
    }
  }
//   // Set edgeOptions for Edge browser
//   'ms:edgeOptions': {
//       prefs: {
//        // 0 - Default, 1 - Allow, 2 - Block
//        'profile.managed_default_content_settings.notifications' : 1
//     }
//  }
//  // Set firefoxOptions for Firefox browser
//  'moz:firefoxOptions': {
//     prefs: {
//       'dom.disable_beforeunload': true,
//       'dom.webnotifications.enabled': false,
//       // 0 - Default, 1 - Allow, 2 - Block
//       'permissions.default.desktop-notification': 1,
//     }
// }
}

var driver = new webdriver.Builder()
  .usingServer('http://hub-usw.browserstack.com/wd/hub')
  .withCapabilities(capabilities)
  .build();

driver.get('https://web-push-book.gauntface.com/demos/notification-examples/')
  .then(function() {
    driver.findElement(webdriver.By.xpath("//body/main[1]/p[3]/input[1]")).click()
      .then(function() {
        driver.quit();
      });
  });
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using System.Collections.Generic;
using OpenQA.Selenium.Chrome;

namespace SampleCSharp
{
    public class Program
    {
        static void Main(string[] args)
        {
            RemoteWebDriver driver;
            Dictionary<string, object> profile = new Dictionary<string, object>();
            // 0 - Default, 1 - Allow, 2 - Block
            profile.Add("profile.default_content_setting_values.notifications", 1);
            Dictionary<string, object> chromeOptions = new Dictionary<string, object>();
            chromeOptions.Add("prefs", profile);

            // SET CAPABILITY
            ChromeOptions capability = new ChromeOptions();
            capability.AddAdditionalCapability("browser", "Chrome", true);
            capability.AddAdditionalCapability("browser_version", "latest", true);
            capability.AddAdditionalCapability("os", "Windows", true);
            capability.AddAdditionalCapability("os_version", "10", true);
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME", true);
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY", true);
            capability.AddAdditionalCapability("chromeOptions", chromeOptions, true);

            driver = new RemoteWebDriver(new Uri("http://hub-cloud.browserstack.com/wd/hub/"), capability);
            driver.Navigate().GoToUrl("https://web-push-book.gauntface.com/demos/notification-examples/");
            driver.FindElement(By.XPath("//body/main[1]/p[3]/input[1]")).Click();
            Thread.Sleep(2000);
            driver.Quit();
        }
    }
}

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.chrome.options import Options
import time

# 0 - Default, 1 - Allow, 2 - Block
chrome_options = Options()
chrome_options.add_experimental_option("prefs", { "profile.default_content_setting_values.notifications": 1})
desired_cap = chrome_options.to_capabilities()
desired_cap.update({
  'browser_version': '75.0',
  'os': 'Windows',
  'os_version': '10'
})
driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://web-push-book.gauntface.com/demos/notification-examples/")
driver.find_element_by_xpath("//body/main[1]/p[3]/input[1]").click()
time.sleep(2)
driver.quit()
require 'rubygems'
require 'selenium-webdriver'

# 0 - Default, 1 - Allow, 2 - Block
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"prefs" => { "profile.default_content_setting_values.notifications" => 1 } })
caps['browser'] = 'Chrome'
caps['browser_version'] = '75.0'
caps['os'] = 'Windows'
caps['os_version'] = '10'
driver = Selenium::WebDriver.for(:remote,
  :url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",
  :desired_capabilities => caps)
driver.navigate.to "https://web-push-book.gauntface.com/demos/notification-examples/"
driver.find_element(:xpath, "//body/main[1]/p[3]/input[1]").click;
sleep(2)
driver.quit

When your web application requests for permission to push notifications, the following pop-up appears in mobile devices:

Web Push Notification Request

The snippet below lets you automate an Allow or Block interaction on Android devices when the remote Chrome browser asks for permission to push notifications.

import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.android.AndroidDriver;

import java.net.URL;
import java.util.Set;

public class AllowNotificationPopupMobile {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_KEY + "@hub-cloud.browserstack.com/wd/hub";

  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    caps.setCapability("browser", "Chrome");
    caps.setCapability("browserName", "android");
    caps.setCapability("device", "Samsung Galaxy S10");
    caps.setCapability("realMobile", "true");
    caps.setCapability("os_version", "9.0");
    AppiumDriver driver = new AndroidDriver(new URL(URL), caps);

    driver.get("https://web-push-book.gauntface.com/demos/notification-examples/");
    driver.findElement(By.xpath("//body/main[1]/p[3]/input[1]")).click();
    Thread.sleep(2000);

    Set contextHandles = driver.getContextHandles();
    // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
    driver.context("NATIVE_APP");
    driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
    Thread.sleep(2000);
    driver.quit();
  }
}
let webdriver = require('wd');

let capabilities = {
    'os_version': '9.0',
    'device': 'Samsung Galaxy S10',
    'real_mobile': 'true',
    'browserstack.user': 'YOUR_USERNAME',
    'browserstack.key': 'YOUR_ACCESS_KEY'
}

let driver = webdriver.promiseRemote("http://hub-cloud.browserstack.com/wd/hub");
driver.init(capabilities, function() {
  driver.get('https://web-push-book.gauntface.com/demos/notification-examples/')
    .then(function() {
      (async () => {
        let element = await driver.element("xpath", "//body/main[1]/p[3]/input[1]");
        await element.click();

        // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
        await driver.context('NATIVE_APP');
        let element2 = await driver.element("xpath", ".//android.widget.Button[@text='Allow']")
        await element2.click();
        await driver.quit();
      })();
    });
});
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using System.Threading;
using OpenQA.Selenium.Appium.Android;
using OpenQA.Selenium.Appium;

namespace SampleCSharp
{
    class AllowNotificationPopup
    {
        static void Main(string[] args)
        {
            AppiumOptions capability = new AppiumOptions();
            capability.AddAdditionalCapability("device", "Samsung Galaxy S10");
            capability.AddAdditionalCapability("os_version", "9.0");
            capability.AddAdditionalCapability("real_mobile", "true");
            capability.AddAdditionalCapability("browserstack.debug", "true");
            capability.AddAdditionalCapability("browserstack.user", "YOUR_USERNAME");
            capability.AddAdditionalCapability("browserstack.key", "YOUR_ACCESS_KEY");
            AndroidDriver<IWebElement> driver = new AndroidDriver<IWebElement>(new Uri("http://hub-cloud.browserstack.com/wd/hub"), capability);
            driver.Navigate().GoToUrl("https://web-push-book.gauntface.com/demos/notification-examples/");
            IWebElement ll = driver.FindElement(By.XPath("//body/main[1]/p[3]/input[1]"));
            ll.Click();
            // To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
            driver.Context = ("NATIVE_APP");
            ll = driver.FindElement(By.XPath(".//android.widget.Button[@text='Allow']"));
            ll.Click();
            Thread.Sleep(2000);
            driver.Quit();
        }
    }
}
import time
from appium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

desired_cap = {
  'device': 'Samsung Galaxy S10',
  'realMobile': 'true',
  'os_version': '9.0'
}
driver = webdriver.Remote(command_executor='http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub.browserstack.com/wd/hub', desired_capabilities=desired_cap)
driver.get("https://web-push-book.gauntface.com/demos/notification-examples/")
driver.find_element_by_xpath("//body/main[1]/p[3]/input[1]").click()
# To accept/block the popup, you need to switch the context to NATIVE_APP and click on the Allow/Block button.
driver.switch_to.context('NATIVE_APP')
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
time.sleep(2)
driver.quit()
require 'rubygems'
require 'appium_lib'

caps = {}
caps['device'] = 'Samsung Galaxy S10'
caps['platformName'] = 'Android'
caps['realMobile'] = 'true'
caps['os_version'] = '9.0'
appium_driver = Appium::Driver.new({
  'caps' => caps,
  'appium_lib' => {
      :server_url => "http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"
  }}, true)
driver = appium_driver.start_driver
driver.navigate.to "https://web-push-book.gauntface.com/demos/notification-examples/"
driver.find_element(:xpath, "//body/main[1]/p[3]/input[1]").click;
# To accept/block the popup, you need to switch the context to “NATIVE_APP“ and click on the Allow/Block button.
driver.set_context('NATIVE_APP')
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
sleep(2)
driver.quit

Note: Web Push Notifications are not supported in iOS devices.

JS alerts

Use the sample code snippets to learn how to disable the most common JS alerts on mobile or desktop devices for any browser. The following image shows the types of JS alerts handled by the sample code snippet. JS Alerts

const { ok } = require('assert');
const webdriver = require('selenium-webdriver'); 

// Input capabilities
const capabilities = {
    'browserName': 'Chrome',
    'os': 'Windows',
    'os_version': '10',
    'browserstack.debug': 'true',
    'build': 'JS alerts pop-ups in Browsers ',
    'name': 'JS alerts popups disabled in Chrome',
}
async function runTestWithCaps () {
  let driver = new webdriver.Builder().usingServer('http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();
  await driver.get("https://the-internet.herokuapp.com/javascript_alerts");
  //   Simple JS alert to confirm.
  const element = await driver.wait(webdriver.until.elementLocated(webdriver.By.css('#content > div > ul > li:nth-child(2) > button')), 5 * 1000);
  await element.click()
  await driver.wait(webdriver.until.alertIsPresent());
  const alertWindow = await driver.switchTo().alert();
  await alertWindow.accept();

  //   Simple JS alert to accept ok.
//   const element = await driver.wait(webdriver.until.elementLocated(webdriver.By.css('#content > div > ul > li:nth-child(1) > button')), 5 * 1000);
//   await element.click()
//   await driver.wait(webdriver.until.alertIsPresent());
//   const alertWindow = await driver.switchTo().alert();
//   await alertWindow.accept();

  //   Simple JS alert to enter data and accept ok.
//   const element = await driver.wait(webdriver.until.elementLocated(webdriver.By.css('#content > div > ul > li:nth-child(3) > button')), 5 * 1000);
//   await element.click()
//   await driver.wait(webdriver.until.alertIsPresent());
//   const alertWindow = await driver.switchTo().alert();
//   await alertWindow.sendKeys('Selenium');
//   await alertWindow.accept();

  await driver.quit();
}
runTestWithCaps(); 

Handle switching tabs in iOS devices

When testing applications that require clicking an element that opens in a new tab, you need to set the safariAllowPopups and autoAcceptAlerts capabilities to true, and then click the required element.

const webdriver = require('selenium-webdriver')

const desiredCaps = {
  'os_version': '14',
  'browserName': 'iPhone',
  'device': 'iPhone 12',
  'real_mobile': 'true',
  'browserstack.debug': 'true',
  'build': 'JS alerts pop-ups in Browsers',
  'name': 'JS alerts popups disabled in Chrome',
  'browserstack.appium_version': '1.18.0',
  'autoAcceptAlerts': 'true',
  'safariAllowPopups' : 'true'
}

const runSampleTest = async () => {
  let driver
  try {
    driver = new webdriver.Builder().
      usingServer('http://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub').
      withCapabilities(desiredCaps).
      build()

    await driver.get('https://demoqa.com/browser-windows')
    const elem = await driver.findElement(webdriver.By.xpath('//*[@id="windowButton"]'))
    await elem.click()

  } catch (e) {
    console.log(e)
  } finally {
    if(driver) {
      await driver.quit()
    }
  }
}

runSampleTest()

Handle any app permission pop-up using Native context

When you test any web application on iOS or Android devices, the permission pop-ups appear in the form of Allow/Block, Continue/Deny, etc options. To handle such pop-ups, irrespective of the options pressented, you can switch to NATIVE_APP context and use locators (by xpath, id, or css) to either allow or block the pop-ups.

Note: When handling permission pop-ups in iOS devices, ensure that the safariAllowPopups capability is set to true before you add any logic to click an element to the script.
driver.context("NATIVE_APP");
//For Android
driver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();
//For iOS
caps.setCapability("safariAllowPopups", true)
driver.findElement(By.id("Allow")).click();
//Change context back to the main page.
driver.context(WEBVIEW);
await driver.context('NATIVE_APP');
//For Android
let element = await driver.element("xpath", ".//android.widget.Button[@text='Continue']")
await element.click();
//For iOS
var capabilities = {"safariAllowPopups", "true"}
let element = await driver.element("id", "Allow")
await element.click();
//Change context back to the main page.
driver.context(WEBVIEW);
driver.Context = ("NATIVE_APP");
//For Android
IWebElement ll =  driver.FindElement(By.XPath(".//android.widget.Button[@text='Continue']"));
ll.Click();
//For iOS
caps.SetCapability("safariAllowPopups", true)
IWebElement ll =  driver.FindElement(By.Id("Allow"));
ll.Click();
//Change context back to the main page.
driver.context(WEBVIEW);
driver.switch_to.context('NATIVE_APP')
#For Android
driver.find_element_by_xpath(".//android.widget.Button[@text='Allow']").click()
#For iOS
capabilities: {"safariAllowPopups": "true"}
driver.find_element_by_id("Allow").click()
# Change context back to the main page.
driver.context(WEBVIEW);
driver.set_context('NATIVE_APP')
#For Android
driver.find_element(:xpath, ".//android.widget.Button[@text='Allow']").click;
#For iOS
caps["safariAllowPopups"] = "true"
driver.find_element(:id, "Allow").click;
//Change context back to the main page.
driver.context(WEBVIEW);
Warning: Disabling the “Save your password” message doesn’t work on the Edge browser.
Edge browser has a known issue that prevents you from either interacting or disabling the Save Your Password pop-up. Check out the GitHub issue link for more details.

Need some help?

If you encounter any pop-up that is not listed on this page, get in touch with Support with your session ID so we can assist you further.

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Talk to an Expert