Get your setup working faster. Join our Discord for optimisation tips from elite testers.Join our Discord
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.
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.
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.
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.
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
Β
Β
Β
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
If you are using BrowserStack SDK, you can set the capabilities covered in this document within the configuration file. To test if the pop-ups appear in Safari or Edge, you can enable pop-ups as follows:
To enable the pop-ups in Edge, set the enablePopups capability to true.
To disable the pop-ups in Safari, set the enablePopups capability to false.
```yml
os: OS X
osVersion: Big Sur
browserName: Safari
browserVersion: 14.1
safari:
driver: 2.45 #Set the driver version you want to use
enablePopups: false
```
BrowserStack SDK is a plug-n-play solution that takes care of all the integration steps for you. Using the BrowserStack SDK is the recommended integration method for your project. To know more, visit the SDK core concepts page.
To test if the pop-ups appear in Safari or IE, you can enable pop-ups as follows:
desired_cap={'browser':'chrome','browser_version':'latest','os':'Windows','os_version':'11','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
constwebdriver=require('selenium-webdriver');// Input capabilitiesconstcapabilities={//To test on mobiles devices, use these capabilities.// 'browserName': 'Safari',// 'os_version': '14',// 'device': 'iPhone 15',// 'real_mobile': 'true','browserName':'Chrome','os':'Windows','os_version':'11','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"]}}asyncfunctionrunSampleTest(){letdriver;try{driver=newwebdriver.Builder().usingServer('https://hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();awaitdriver.get('https://www.webroot.com/services/popuptester1.htm');consttitle=awaitdriver.getTitle();console.log(title);}catch(e){console.log(e);}finally{if(driver){awaitdriver.quit();}}}runSampleTest();
constwebdriver=require('selenium-webdriver');// Input capabilitiesconstcapabilities={'browserName':'Firefox','os':'Windows','os_version':'11','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,}}}asyncfunctionrunSampleTest(){letdriver;try{driver=newwebdriver.Builder().usingServer('https://hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();awaitdriver.get('https://www.webroot.com/services/popuptester1.htm');consttitle=awaitdriver.getTitle();console.log(title);}catch(e){console.log(e);}finally{if(driver){awaitdriver.quit();}}}runSampleTest();
constwebdriver=require('selenium-webdriver');// Input capabilitiesconstcapabilities={'browserName':'Edge','os':'Windows','os_version':'11','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"]}}asyncfunctionrunSampleTest(){letdriver;try{driver=newwebdriver.Builder().usingServer('https://hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();awaitdriver.get('https://www.webroot.com/services/popuptester1.htm');consttitle=awaitdriver.getTitle();console.log(title);}catch(e){console.log(e);}finally{if(driver){awaitdriver.quit();}}}runSampleTest();
Know your location pop-up
Use the sample code snippets to disable the know your location pop-up in the following devices.
importorg.openqa.selenium.By;importorg.openqa.selenium.JavascriptExecutor;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.firefox.FirefoxOptions;importorg.openqa.selenium.firefox.FirefoxProfile;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.testng.annotations.AfterTest;importorg.testng.annotations.BeforeTest;importorg.testng.annotations.Test;importjava.net.URL;importjava.util.HashMap;publicclassTicket_991348_Replicate_Firefox_Profile_Location{publicstaticfinalStringUSERNAME="<BROWSERSTACK_USERNAME>";publicstaticfinalStringAUTOMATE_KEY="<BROWSERSTACK_ACCESS_KEY>";publicstaticfinalStringURL="https://"+USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";FirefoxOptionscapabilities=newFirefoxOptions();FirefoxProfilefirefoxProfile=newFirefoxProfile();RemoteWebDriverremoteWebDriver=null;JavascriptExecutorjavascriptExecutor=null;@BeforeTestpublicvoidsetExecutionEnvironment()throwsException{capabilities.setCapability("browserName","Firefox");capabilities.setCapability("browserVersion","latest");HashMap<String,Object>browserstackOptions=newHashMap<String,Object>();browserstackOptions.put("os","Windows");browserstackOptions.put("osVersion","11");browserstackOptions.put("projectName","Ticket_991348_Replicate_Firefox_Profile_Location_Project");browserstackOptions.put("buildName","Ticket_991348_Replicate_Firefox_Profile_Location_Build_1.0.0");browserstackOptions.put("sessionName","Ticket_991348_Replicate_Firefox_Profile_Location_Session - Geo");browserstackOptions.put("buildTag","Firefox Profile");browserstackOptions.put("debug","true");HashMap<String,Boolean>networkLogsOptions=newHashMap<>();networkLogsOptions.put("captureContent",true);browserstackOptions.put("networkLogs","true");browserstackOptions.put("networkLogsOptions",networkLogsOptions);browserstackOptions.put("seleniumVersion","4.11.0");browserstackOptions.put("consoleLogs","errors");firefoxProfile.setPreference("permissions.default.geo",1);//1-allow; 2-blockcapabilities.setCapability("bstack:options",browserstackOptions);capabilities.setProfile(firefoxProfile);}@TestpublicvoidfirefoxProfileGeolocation()throwsException{try{remoteWebDriver=newRemoteWebDriver(newURL(URL),capabilities);remoteWebDriver.get("https://the-internet.herokuapp.com/geolocation");remoteWebDriver.manage().window().maximize();Thread.sleep(5000);remoteWebDriver.findElement(By.xpath("//button[text()='Where am I?']")).click();Thread.sleep(5000);remoteWebDriver.findElement(By.xpath("//p[contains(text(),'Latitude:')]"));mark("passed","As all the steps have successfully completed",remoteWebDriver);}catch(Exceptione){e.printStackTrace();mark("failed","As all the steps have not successfully completed",remoteWebDriver);}}@AfterTestpublicvoidcleanExecutionEnvironment()throwsException{remoteWebDriver.quit();System.out.println("Test Finished");}// Method to mark test as pass / fail on BrowserStackpublicstaticvoidmark(Stringstatus,Stringreason,WebDriverremoteWebDriver){JavascriptExecutorjse=(JavascriptExecutor)remoteWebDriver;jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");}}
To automate the accept action of the popup on Firefox browser, use the following code:
importorg.openqa.selenium.By;importorg.openqa.selenium.JavascriptExecutor;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.firefox.FirefoxOptions;importorg.openqa.selenium.firefox.FirefoxProfile;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.testng.annotations.AfterTest;importorg.testng.annotations.BeforeTest;importorg.testng.annotations.Test;importjava.net.URL;importjava.util.HashMap;publicclassTicket_991348_Replicate_Firefox_Profile_Location{publicstaticfinalStringUSERNAME="<BROWSERSTACK_USERNAME>";publicstaticfinalStringAUTOMATE_KEY="<BROWSERSTACK_ACCESS_KEY>";publicstaticfinalStringURL="https://"+USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";FirefoxOptionscapabilities=newFirefoxOptions();FirefoxProfilefirefoxProfile=newFirefoxProfile();RemoteWebDriverremoteWebDriver=null;JavascriptExecutorjavascriptExecutor=null;@BeforeTestpublicvoidsetExecutionEnvironment()throwsException{capabilities.setCapability("browserName","Firefox");capabilities.setCapability("browserVersion","latest");HashMap<String,Object>browserstackOptions=newHashMap<String,Object>();browserstackOptions.put("os","Windows");browserstackOptions.put("osVersion","11");browserstackOptions.put("projectName","Ticket_991348_Replicate_Firefox_Profile_Location_Project");browserstackOptions.put("buildName","Ticket_991348_Replicate_Firefox_Profile_Location_Build_1.0.0");browserstackOptions.put("sessionName","Ticket_991348_Replicate_Firefox_Profile_Location_Session - Geo");browserstackOptions.put("buildTag","Firefox Profile");browserstackOptions.put("debug","true");HashMap<String,Boolean>networkLogsOptions=newHashMap<>();networkLogsOptions.put("captureContent",true);browserstackOptions.put("networkLogs","true");browserstackOptions.put("networkLogsOptions",networkLogsOptions);browserstackOptions.put("seleniumVersion","4.11.0");browserstackOptions.put("consoleLogs","errors");firefoxProfile.setPreference("geo.enabled",true);firefoxProfile.setPreference("geo.prompt.testing",true);firefoxProfile.setPreference("geo.prompt.testing.allow",true);capabilities.setCapability("bstack:options",browserstackOptions);capabilities.setProfile(firefoxProfile);}@TestpublicvoidfirefoxProfileGeolocation()throwsException{try{remoteWebDriver=newRemoteWebDriver(newURL(URL),capabilities);remoteWebDriver.get("https://the-internet.herokuapp.com/geolocation");remoteWebDriver.manage().window().maximize();Thread.sleep(5000);remoteWebDriver.findElement(By.xpath("//button[text()='Where am I?']")).click();Thread.sleep(5000);remoteWebDriver.findElement(By.xpath("//p[contains(text(),'Latitude:')]"));mark("passed","As all the steps have successfully completed",remoteWebDriver);}catch(Exceptione){e.printStackTrace();mark("failed","As all the steps have not successfully completed",remoteWebDriver);}}@AfterTestpublicvoidcleanExecutionEnvironment()throwsException{remoteWebDriver.quit();System.out.println("Test Finished");}// Method to mark test as pass / fail on BrowserStackpublicstaticvoidmark(Stringstatus,Stringreason,WebDriverremoteWebDriver){JavascriptExecutorjse=(JavascriptExecutor)remoteWebDriver;jse.executeScript("browserstack_executor: {\"action\": \"setSessionStatus\", \"arguments\": {\"status\": \""+status+"\", \"reason\": \""+reason+"\"}}");}}
When a web application requests access to the location, the following pop-ups appear mobile device where the test is running:
The following snippet lets you automate an Allow or Block interaction when the remote browser requests a mobile device for location.
importorg.openqa.selenium.By;importorg.openqa.selenium.remote.DesiredCapabilities;importio.appium.java_client.AppiumDriver;importio.appium.java_client.android.AndroidDriver;importjava.net.URL;importjava.util.Set;publicclassAllowGeoLocationPopup{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("browser","Chrome");caps.setCapability("browserName","android");caps.setCapability("device","Samsung Galaxy S23");caps.setCapability("realMobile","true");caps.setCapability("os_version","9.0");AppiumDriverdriver=newAndroidDriver(newURL(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();}}
// use the following webdriverIO code snippet to accept/block the popup// update your caps to include the followingcapabilities={'goog:chromeOptions':{prefs:{// 0 - Default, 1 - Allow, 2 - Block'profile.managed_default_content_settings.geolocation':1}}}// get a list of available contextsconstcontexts=awaitbrowser.getContexts()// switch the context to "NATIVE_APP"awaitbrowser.switchContext(contexts[0])// Set text to "Block" to block the permission.constpopUp=await$('.//android.widget.Button[@text="Allow"]')awaitpopUp.click()// switch context back to the main pageawaitbrowser.switchContext(contexts[1])
usingSystem;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingSystem.Threading;usingSystem.Collections.Generic;usingOpenQA.Selenium.Appium;usingOpenQA.Selenium.Appium.Android;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Appium.iOS;namespaceSampleCSharp{classProgram{publicstaticvoidMain(string[]args){AppiumOptionscapability=newAppiumOptions();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=newAndroidDriver<IWebElement>(newUri("https://hub-cloud.browserstack.com/wd/hub"),capability);driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/geolocation");Thread.Sleep(5000);IWebElementll=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();}}}
importtimefromappiumimportwebdriverfromselenium.webdriver.common.desired_capabilitiesimportDesiredCapabilitiesdesired_cap={'device':'Samsung Galaxy S23','realMobile':'true','os_version':'9.0'}driver=webdriver.Remote(command_executor='https://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 S23'caps['platformName']='Android'caps['realMobile']='true'caps['os_version']='9.0'appium_driver=Appium::Driver.new({'caps'=>caps,'appium_lib'=>{:server_url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}},true)driver=appium_driver.start_driverdriver.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
importorg.openqa.selenium.By;importorg.openqa.selenium.remote.DesiredCapabilities;importio.appium.java_client.AppiumDriver;importio.appium.java_client.ios.IOSDriver;importio.appium.java_client.ios.IOSElement;importjava.net.URL;importjava.util.Set;publicclassAllowGeoLocationPopup{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("os_version","14");caps.setCapability("device","iPhone 15");caps.setCapability("realMobile","true");IOSDriver<IOSElement>driver=newIOSDriver<IOSElement>(newURL("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();}}
constwebdriver=require('selenium-webdriver');// SET CAPABILITYconstcapabilities={os_version:'14',device:'iPhone 15',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',browserName:'safari'};construnSampleTest=asynccapabilities=>{letdriver;try{driver=newwebdriver.Builder().usingServer(`https://hub.browserstack.com/wd/hub`).withCapabilities(capabilities).build();awaitdriver.get('https://the-internet.herokuapp.com/geolocation');constelement=awaitdriver.findElement(webdriver.By.xpath("//button[contains(text(),'Where am I?')]"));awaitelement.click();}catch(e){console.log(e);}finally{if(driver){awaitdriver.quit();}}};runSampleTest(capabilities);
usingSystem;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingSystem.Threading;usingSystem.Collections.Generic;usingOpenQA.Selenium.Appium;usingOpenQA.Selenium.Chrome;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Appium.iOS;namespaceSampleCSharp{classProgram{publicstaticvoidMain(string[]args){AppiumOptionscapability=newAppiumOptions();capability.AddAdditionalCapability("device","iPhone 15");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=newIOSDriver<IWebElement>(newUri("https://u:p@hub-cloud.browserstack.com/wd/hub/"),capability);driver.Navigate().GoToUrl("https://the-internet.herokuapp.com/geolocation");Thread.Sleep(5000);IWebElementll=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();}}}
importtimefromappiumimportwebdriverfromselenium.webdriver.common.desired_capabilitiesimportDesiredCapabilitiesdesired_cap={"os_version":"14","device":"iPhone 15","real_mobile":"true",}driver=webdriver.Remote(command_executor='https://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 15'caps['platformName']='iOS'caps['realMobile']='true'caps['os_version']='14'appium_driver=Appium::Driver.new({'caps'=>caps,'appium_lib'=>{:server_url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}},true)driver=appium_driver.start_driverdriver.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.
importorg.openqa.selenium.By;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.chrome.ChromeOptions;importorg.openqa.selenium.remote.DesiredCapabilities;importorg.openqa.selenium.remote.RemoteWebDriver;importjava.net.URL;publicclassAllowCameraPopupChrome{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{//Configure ChromeOptions to pass fake media streamChromeOptionsoptions=newChromeOptions();options.addArguments("use-fake-device-for-media-stream");options.addArguments("use-fake-ui-for-media-stream");DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("browser","Chrome");caps.setCapability("browser_version","128.0");caps.setCapability("os","Windows");caps.setCapability("os_version","11");caps.setCapability(ChromeOptions.CAPABILITY,options);WebDriverdriver=newRemoteWebDriver(newURL(URL),caps);//WebCam Testdriver.get("https://webcamtests.com/check");Thread.sleep(5000);driver.findElement(By.id("webcam-launcher")).click();Thread.sleep(2000);//Mic Testdriver.get("https://www.vidyard.com/mic-test/");Thread.sleep(2000);driver.findElement(By.xpath("//a[@id='start-test']")).click();Thread.sleep(2000);driver.quit();}}
varwebdriver=require('selenium-webdriver');varchrome=require("selenium-webdriver/chrome");const{By}=require('selenium-webdriver');varcapabilities={'browserName':'Chrome','browser_version':'95.0','os':'Windows','os_version':'11','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,// }// }}asyncfunctionrunTestWithCaps(){letdriver=newwebdriver.Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();awaitdriver.get("https://webcamtests.com/check");varx=awaitdriver.wait(webdriver.until.elementIsVisible(driver.findElement(By.xpath('//*[@id="webcam-launcher"]'),1000)));awaitx.click()awaitdriver.get("https://www.vidyard.com/mic-test/");varelements=awaitdriver.wait(driver.findElements(By.css('#gdpr-banner > div > button'),1000));if(elements.length>0){awaitelements[0].click()}y=awaitdriver.wait(webdriver.until.elementIsVisible(driver.findElement(By.xpath('//*[@id="start-test"]'),1000)));// await sleep(5000);awaity.click()awaitdriver.quit();}runTestWithCaps();
usingSystem;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingSystem.Threading;usingOpenQA.Selenium.Chrome;namespaceSampleCSharp{publicclassAllowCameraMicPopupChrome{staticvoidMain(string[]args){IWebDriverdriver;//Configure ChromeOptions to pass fake media streamChromeOptionschromeOptions=newChromeOptions();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","128.0",true);chromeOptions.AddAdditionalCapability("os","Windows",true);chromeOptions.AddAdditionalCapability("os_version","11",true);chromeOptions.AddAdditionalCapability("browserstack.user","YOUR_USERNAME",true);chromeOptions.AddAdditionalCapability("browserstack.key","YOUR_ACCESS_KEY",true);driver=newRemoteWebDriver(newUri("https://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 Testdriver.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();}}}
fromseleniumimportwebdriverfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.common.desired_capabilitiesimportDesiredCapabilitiesfromselenium.webdriver.chrome.optionsimportOptionsimporttimedesired_cap={'browser_version':'128.0','os':'Windows','os_version':'11',#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='https://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 streamcaps=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']='128.0'caps['os']='Windows'caps['os_version']='11'driver=Selenium::WebDriver.for(:remote,:url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",:desired_capabilities=>caps)# WebCam Testdriver.navigate.to"https://webcamtests.com/check"sleep(5)driver.find_element(:id,"webcam-launcher").click;sleep(5)#Mic Testdriver.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 appear in the mobile device:
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.
importorg.openqa.selenium.By;importorg.openqa.selenium.remote.DesiredCapabilities;importio.appium.java_client.AppiumDriver;importio.appium.java_client.android.AndroidDriver;importjava.net.URL;publicclassAllowCameraPopupChromeMobile{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("browser","Chrome");caps.setCapability("device","Samsung Galaxy S23");caps.setCapability("realMobile","true");caps.setCapability("os_version","9.0");AppiumDriverdriver=newAndroidDriver(newURL(URL),caps);//WebCam Testdriver.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 Testdriver.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();}}
// use the following webdriverIO code snippet to accept/block the popup// get a list of available contextsconstcontexts=awaitbrowser.getContexts()// switch the context to "NATIVE_APP"awaitbrowser.switchContext(contexts[0])// Set text to "Block" to block the permission.constpopUp=await$('.//android.widget.Button[@text="Allow"]')awaitpopUp.click()// switch context back to the main pageawaitbrowser.switchContext(contexts[1])
usingSystem;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingSystem.Threading;usingOpenQA.Selenium.Appium.Android;usingOpenQA.Selenium.Appium;namespaceSampleCSharp{classProgram{staticvoidMain(string[]args){AppiumOptionscapability=newAppiumOptions();capability.AddAdditionalCapability("device","Samsung Galaxy S23");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=newAndroidDriver<IWebElement>(newUri("https://hub-cloud.browserstack.com/wd/hub"),capability);// Camera Testdriver.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 Testdriver.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();}}}
importtimefromappiumimportwebdriverfromselenium.webdriver.common.desired_capabilitiesimportDesiredCapabilitiesdesired_cap={'device':'Samsung Galaxy S23','realMobile':'true','os_version':'9.0'}driver=webdriver.Remote(command_executor='https://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 S23'caps['platformName']='Android'caps['realMobile']='true'caps['os_version']='9.0'appium_driver=Appium::Driver.new({'caps'=>caps,'appium_lib'=>{:server_url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}},true)driver=appium_driver.start_driver# WebCam Testdriver.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 Testdriver.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
importorg.openqa.selenium.By;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.remote.DesiredCapabilities;importio.appium.java_client.AppiumDriver;importio.appium.java_client.ios.IOSDriver;importio.appium.java_client.ios.IOSElement;importjava.net.URL;importjava.util.Set;publicclasscamera{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("device","iPhone 15");caps.setCapability("realMobile","true");caps.setCapability("os_version","14.0");caps.setCapability("device","iPhone 15");caps.setCapability("nativeWebTap","true");IOSDriver<IOSElement>driver=newIOSDriver<IOSElement>(newURL("https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub"),caps);//WebCam Testdriver.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");WebElementele=driver.findElement(By.id("Allow"));ele.click();Thread.sleep(5000);Set<String>contextNames=driver.getContextHandles();driver.context(contextNames.toArray()[1].toString());//Mic Testdriver.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();}}
// use the following webdriverIO code snippet to accept/block the popup// get a list of available contextsconstcontexts=awaitbrowser.getContexts()// switch the context to "NATIVE_APP"awaitbrowser.switchContext(contexts[0])// Set text to "Cancel" to block the permission.constpopUp=await$('[name="Allow"]')awaitpopUp.click()// switch context back to the main pageawaitbrowser.switchContext(contexts[1])
usingSystem;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingSystem.Threading;usingOpenQA.Selenium.Appium.iOS;usingOpenQA.Selenium.Appium;namespaceSampleCSharp{classProgram{staticvoidMain(string[]args){AppiumOptionscapability=newAppiumOptions();capability.AddAdditionalCapability("device","iPhone 15");capability.AddAdditionalCapability("os_version","14");capability.AddAdditionalCapability("real_mobile","true");capability.AddAdditionalCapability("browserstack.debug","true");IOSDriver<IWebElement>driver=newIOSDriver<IWebElement>(newUri("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");IWebElementele=driver.FindElement(By.Id("Allow"));ele.Click();driver.Context=driver.Contexts[1];Thread.Sleep(2000);driver.Navigate().GoToUrl("https://www.vidyard.com/mic-test/");IWebElementll=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();}}}
When your web application requests for permission to push notifications, the following pop-up appears in mobile devices:
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.
importorg.openqa.selenium.By;importorg.openqa.selenium.remote.DesiredCapabilities;importio.appium.java_client.AppiumDriver;importio.appium.java_client.android.AndroidDriver;importjava.net.URL;importjava.util.Set;publicclassAllowNotificationPopupMobile{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=newDesiredCapabilities();caps.setCapability("browser","Chrome");caps.setCapability("browserName","android");caps.setCapability("device","Samsung Galaxy S23");caps.setCapability("realMobile","true");caps.setCapability("os_version","9.0");AppiumDriverdriver=newAndroidDriver(newURL(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);SetcontextHandles=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();}}
// use the following webdriverIO code snippet to accept/block the popup// get a list of available contextsconstcontexts=awaitbrowser.getContexts()// switch the context to "NATIVE_APP"awaitbrowser.switchContext(contexts[0])// Set text to "Block" to block the permission.constpopUp=await$('.//android.widget.Button[@text="Allow"]')awaitpopUp.click()// switch context back to the main pageawaitbrowser.switchContext(contexts[1])
usingSystem;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingSystem.Threading;usingOpenQA.Selenium.Appium.Android;usingOpenQA.Selenium.Appium;namespaceSampleCSharp{classAllowNotificationPopup{staticvoidMain(string[]args){AppiumOptionscapability=newAppiumOptions();capability.AddAdditionalCapability("device","Samsung Galaxy S23");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=newAndroidDriver<IWebElement>(newUri("https://hub-cloud.browserstack.com/wd/hub"),capability);driver.Navigate().GoToUrl("https://web-push-book.gauntface.com/demos/notification-examples/");IWebElementll=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();}}}
importtimefromappiumimportwebdriverfromselenium.webdriver.common.desired_capabilitiesimportDesiredCapabilitiesdesired_cap={'device':'Samsung Galaxy S23','realMobile':'true','os_version':'9.0'}driver=webdriver.Remote(command_executor='https://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 S23'caps['platformName']='Android'caps['realMobile']='true'caps['os_version']='9.0'appium_driver=Appium::Driver.new({'caps'=>caps,'appium_lib'=>{:server_url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub"}},true)driver=appium_driver.start_driverdriver.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.
const{ok}=require('assert');constwebdriver=require('selenium-webdriver');// Input capabilitiesconstcapabilities={'browserName':'Chrome','os':'Windows','os_version':'11','browserstack.debug':'true','build':'JS alerts pop-ups in Browsers ','name':'JS alerts popups disabled in Chrome',}asyncfunctionrunTestWithCaps(){letdriver=newwebdriver.Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(capabilities).build();awaitdriver.get("https://the-internet.herokuapp.com/javascript_alerts");// Simple JS alert to confirm.constelement=awaitdriver.wait(webdriver.until.elementLocated(webdriver.By.css('#content > div > ul > li:nth-child(2) > button')),5*1000);awaitelement.click()awaitdriver.wait(webdriver.until.alertIsPresent());constalertWindow=awaitdriver.switchTo().alert();awaitalertWindow.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();awaitdriver.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.
constwebdriver=require('selenium-webdriver')constdesiredCaps={'os_version':'14','browserName':'iPhone','device':'iPhone 15','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'}construnSampleTest=async()=>{letdrivertry{driver=newwebdriver.Builder().usingServer('https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub').withCapabilities(desiredCaps).build()awaitdriver.get('https://demoqa.com/browser-windows')constelem=awaitdriver.findElement(webdriver.By.xpath('//*[@id="windowButton"]'))awaitelem.click()}catch(e){console.log(e)}finally{if(driver){awaitdriver.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 presented, you can switch to NATIVE_APP context and use locators (by xpath, id, or css) to either allow or block the pop-ups.
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 Androiddriver.findElement(By.xpath(".//android.widget.Button[@text='Allow']")).click();//For iOScaps.setCapability("safariAllowPopups",true)driver.findElement(By.id("Allow")).click();//Change context back to the main page.driver.context(βWEBVIEWβ);
// use the following webdriverIO code snippet to accept/block the popup// get a list of available contextsconstcontexts=awaitbrowser.getContexts()// switch the context to "NATIVE_APP"awaitbrowser.switchContext(contexts[0])// For AndroidconstpopUpAndroid=await$(".//android.widget.Button[@text='Continue']")awaitpopUpAndroid.click()// For iOS// Update caps to includeconstcapabilities={"safariAllowPopups":"true"}constpopUpIOS=await$('.//android.widget.Button[@text="Allow"]')awaitpopUpIOS.click()// switch context back to the main pageawaitbrowser.switchContext(contexts[1])
driver.Context=("NATIVE_APP");//For AndroidIWebElementll=driver.FindElement(By.XPath(".//android.widget.Button[@text='Continue']"));ll.Click();//For iOScaps.SetCapability("safariAllowPopups",true)IWebElementll=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β);
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.
Did this page help you?
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
Test web and mobile, from manual to automation, on real devices in one unified platform.