Cross-Origin Resource Sharing (CORS) is a mechanism that enables web pages to access resources running on a restricted or different domain. BrowserStack provides the disableCorsRestrictions capability to disable CORS restrictions on the Safari browser.
Using the disableCorsRestrictions capability in your test script enables your publicly available or locally-hosted website to access resources from another domain, server, or APIs.
Disabling CORS restriction may cause security issues in your website under test. Use this capability only after careful consideration.
Sample screenshots with and without CORS restriction
The following sample screenshots show the content of https://polar-inlet-22085.herokuapp.com with and without CORS restriction disabled:
In the following example test script, we run a sample test that disables CORS restriction, opens https://polar-inlet-22085.herokuapp.com on Safari browser, and prints screenshot of the web page in the Text Logs section of the Automate session dashboard:
importorg.openqa.selenium.TakesScreenshot;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.OutputType;importjava.util.concurrent.TimeUnit;importjava.net.URL;importjava.time.Duration;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassJavaSample{WebDriver driver =newRemoteWebDriver(newURL(URL), caps);try{
driver.get("https://polar-inlet-22085.herokuapp.com/");newWebDriverWait(driver,Duration.ofSeconds(10)).until(ExpectedConditions.titleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelyTimeUnit.SECONDS.sleep(5);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver =(RemoteWebDriver)newAugmenter().augment(driver);((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);}catch(Exception e){// print any exception in the IDE's consoleSystem.out.println(e);}
driver.quit();}}
const webdriver =require('selenium-webdriver');asyncfunctionrunTestWithCaps(){try{await driver.get("https://polar-inlet-22085.herokuapp.com/");await driver.wait(webdriver.until.titleMatches(/CORS test/i),10000);// wait for 5 seconds for the web page to load completelyawaitnewPromise(resolve=>setTimeout(resolve,5000));//print screenshot of the web page in the 'Text Logs' section on your Automate session dashboardawait driver.takeScreenshot();}catch( e ){
console.log("Error:", e.message)}await driver.quit();}runTestWithCaps();
sing System;usingSystem.Threading;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Support.UI;namespaceSeleniumTest{publicclassScreenShotRemoteWebDriver:RemoteWebDriver,ITakesScreenshot{publicScreenShotRemoteWebDriver(Uri uri,OpenQA.Selenium.Safari.SafariOptions dc):base(uri, dc)publicnewScreenshotGetScreenshot(){Response screenshotResponse =this.Execute(DriverCommand.Screenshot,null);string base64 = screenshotResponse.Value.ToString();returnnewScreenshot(base64);}}classProgram{staticvoidMain(string[] args){try{
driver.Navigate().GoToUrl("https://polar-inlet-22085.herokuapp.com/");// wait for 10 seconds until the browser title matches 'CORS Tester'var wait =newWebDriverWait(driver,newTimeSpan(0,0,10));var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleIs("CORS Tester"));// wait for 5 seconds for the web page to load completely
Thread.Sleep(5000);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboardITakesScreenshot screenshotDriver = driver asITakesScreenshot;
screenshotDriver.GetScreenshot();}catch{
Console.WriteLine("Exception: Title did not match");}
driver.Quit();}}}
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
try:
driver.get("https://polar-inlet-22085.herokuapp.com")
WebDriverWait(driver,10).until(EC.title_contains("CORS Tester"))# wait for 5 seconds for the web page to load completely
time.sleep(5)# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver.save_screenshot('screenshots.png')except:print("An exception occurred - Title did not match 'CORS Tester'")finally:
driver.quit()
After you run the test script, a screenshot of the web page is displayed in the Text Logs section of your Automate session dashboard, as shown in the following image:
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.
In the following example test script, we run a sample test that disables CORS restriction, opens https://polar-inlet-22085.herokuapp.com on Safari browser, and prints screenshot of the web page in the Text Logs section of the Automate session dashboard:
importorg.openqa.selenium.TakesScreenshot;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.DesiredCapabilities;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.OutputType;importjava.util.concurrent.TimeUnit;importjava.net.URL;importjava.time.Duration;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassJavaSample{publicstaticfinalString AUTOMATE_USERNAME ="YOUR_USERNAME";publicstaticfinalString AUTOMATE_ACCESS_KEY ="YOUR_ACCESS_KEY";publicstaticfinalString URL ="https://"+ AUTOMATE_USERNAME +":"+ AUTOMATE_ACCESS_KEY +"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[] args)throwsException{DesiredCapabilities capabilities =newDesiredCapabilities();
capabilities.setCapability("browserName","Safari");
capabilities.setCapability("browserVersion","15.0");HashMap<String,Object> browserstackOptions =newHashMap<String,Object>();
browserstackOptions.put("os","OS X");
browserstackOptions.put("osVersion","Monterey");
browserstackOptions.put("projectName","BrowserStack - CORS test");
browserstackOptions.put("buildName","BStack Sample Test");
browserstackOptions.put("disableCorsRestrictions","true");
capabilities.setCapability("bstack:options", browserstackOptions);WebDriver driver =newRemoteWebDriver(newURL(URL), caps);try{
driver.get("https://polar-inlet-22085.herokuapp.com/");newWebDriverWait(driver,Duration.ofSeconds(10)).until(ExpectedConditions.titleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelyTimeUnit.SECONDS.sleep(5);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver =(RemoteWebDriver)newAugmenter().augment(driver);((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);}catch(Exception e){// print any exception in the IDE's consoleSystem.out.println(e);}
driver.quit();}}
const webdriver =require('selenium-webdriver');// Input capabilitiesconst capabilities ={'bstack:options':{"os":"OS X","osVersion":"Monterey","projectName":"BrowserStack - CORS test","buildName":"BStack Sample Test","disableCorsRestrictions":"true",},"browserName":"Safari","browserVersion":"15.0",}asyncfunctionrunTestWithCaps(){let driver =newwebdriver.Builder().usingServer(`https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub`).withCapabilities(capabilities).build();try{await driver.get("https://polar-inlet-22085.herokuapp.com/");await driver.wait(webdriver.until.titleMatches(/CORS test/i),10000);// wait for 5 seconds for the web page to load completelyawaitnewPromise(resolve=>setTimeout(resolve,5000));//print screenshot of the web page in the 'Text Logs' section on your Automate session dashboardawait driver.takeScreenshot();}catch( e ){
console.log("Error:", e.message)}await driver.quit();}runTestWithCaps();
sing System;usingSystem.Threading;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Support.UI;namespaceSeleniumTest{publicclassScreenShotRemoteWebDriver:RemoteWebDriver,ITakesScreenshot{publicScreenShotRemoteWebDriver(Uri uri,OpenQA.Selenium.Safari.SafariOptions dc):base(uri, dc){}publicnewScreenshotGetScreenshot(){Response screenshotResponse =this.Execute(DriverCommand.Screenshot,null);string base64 = screenshotResponse.Value.ToString();returnnewScreenshot(base64);}}classProgram{staticvoidMain(string[] args){ScreenShotRemoteWebDriver driver;SafariOptions capabilities =newSafariOptions();
capabilities.BrowserVersion ="15.0";Dictionary<string,object> browserstackOptions =newDictionary<string,object>();
browserstackOptions.Add("os","OS X");
browserstackOptions.Add("osVersion","Monterey");
browserstackOptions.Add("projectName","BrowserStack - CORS test");
browserstackOptions.Add("buildName","BStack Sample Test");
browserstackOptions.Add("disableCorsRestrictions","true");
browserstackOptions.Add("userName","YOUR_USERNAME");
browserstackOptions.Add("accessKey","YOUR_ACCESS_KEY");
browserstackOptions.Add("browserName","Safari");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
driver =newScreenShotRemoteWebDriver(newUri("https://hub-cloud.browserstack.com/wd/hub/"), capability);try{
driver.Navigate().GoToUrl("https://polar-inlet-22085.herokuapp.com/");// wait for 10 seconds until the browser title matches 'CORS Tester'var wait =newWebDriverWait(driver,newTimeSpan(0,0,10));var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleIs("CORS Tester"));// wait for 5 seconds for the web page to load completely
Thread.Sleep(5000);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboardITakesScreenshot screenshotDriver = driver asITakesScreenshot;
screenshotDriver.GetScreenshot();}catch{
Console.WriteLine("Exception: Title did not match");}
driver.Quit();}}}
<?phprequire_once('vendor/autoload.php');useFacebook\WebDriver\Remote\RemoteWebDriver;useFacebook\WebDriver\WebDriverBy;useFacebook\WebDriver\WebDriverExpectedCondition;$caps=array('bstack:options'=>array("os"=>"OS X","osVersion"=>"Monterey","projectName"=>"BrowserStack - CORS test","buildName"=>"BStack Sample Test","disableCorsRestrictions"=>"true",),"browserName"=>"Safari","browserVersion"=>"15.0",)$driver=RemoteWebDriver::create("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",$caps);try{$driver->get("https://polar-inlet-22085.herokuapp.com");$driver->wait(10)->until(WebDriverExpectedCondition::titleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelysleep(5);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard$driver->takeScreenshot();}catch(Exception$e){echo'Exception occured';}$driver->quit();?>
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
desired_cap ={'bstack:options':{"os":"OS X","osVersion":"Monterey","projectName":"BrowserStack - CORS test","buildName":"BStack Sample Test","disableCorsRestrictions":"true",},"browserName":"Safari","browserVersion":"15.0",}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub',
desired_capabilities=desired_cap)try:
driver.get("https://polar-inlet-22085.herokuapp.com")
WebDriverWait(driver,10).until(EC.title_contains("CORS Tester"))# wait for 5 seconds for the web page to load completely
time.sleep(5)# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver.save_screenshot('screenshots.png')except:print("An exception occurred - Title did not match 'CORS Tester'")finally:
driver.quit()
require'rubygems'require'selenium-webdriver'# Input capabilities
capabilities ={'bstack:options'=>{"os"=>"OS X","osVersion"=>"Monterey","projectName"=>"BrowserStack - CORS test","buildName"=>"BStack Sample Test","disableCorsRestrictions"=>"true",},"browserName"=>"Safari","browserVersion"=>"15.0",}
driver =Selenium::WebDriver.for(:remote,:url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",:desired_capabilities=> caps)begin
driver.navigate.to "https://polar-inlet-22085.herokuapp.com"
wait =Selenium::WebDriver::Wait.new(:timeout=>10)# seconds
wait.until{!driver.title.match(/CORS Tester/i).nil?}# wait for 5 seconds for the web page to load completely
sleep 5# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver.save_screenshot("screenshots.png")rescue
puts "Exception occured"end
driver.quit
importorg.openqa.selenium.TakesScreenshot;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.remote.Augmenter;importorg.openqa.selenium.remote.DesiredCapabilities;importorg.openqa.selenium.remote.RemoteWebDriver;importorg.openqa.selenium.OutputType;importjava.util.concurrent.TimeUnit;importjava.net.URL;importjava.time.Duration;importorg.openqa.selenium.support.ui.ExpectedConditions;importorg.openqa.selenium.support.ui.WebDriverWait;publicclassJavaSample{publicstaticfinalString AUTOMATE_USERNAME ="YOUR_USERNAME";publicstaticfinalString AUTOMATE_ACCESS_KEY ="YOUR_ACCESS_KEY";publicstaticfinalString URL ="https://"+ AUTOMATE_USERNAME +":"+ AUTOMATE_ACCESS_KEY +"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[] args)throwsException{DesiredCapabilities caps =newDesiredCapabilities();
caps.setCapability("os","OS X");
caps.setCapability("os_version","Catalina");
caps.setCapability("browser","Safari");
caps.setCapability("browser_version","13.0");
caps.setCapability("name","BStack-[Java] Sample Test");// test name
caps.setCapability("build","BrowserStack - CORS test");// CI/CD job or build name
caps.setCapability("browserstack.disableCorsRestrictions","true");WebDriver driver =newRemoteWebDriver(newURL(URL), caps);try{
driver.get("https://polar-inlet-22085.herokuapp.com/");newWebDriverWait(driver,Duration.ofSeconds(10)).until(ExpectedConditions.titleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelyTimeUnit.SECONDS.sleep(5);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver =(RemoteWebDriver)newAugmenter().augment(driver);((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);}catch(Exception e){// print any exception in the IDE's consoleSystem.out.println(e);}
driver.quit();}}
const webdriver =require('selenium-webdriver');// Input capabilitiesconst capabilities ={"os":"OS X","os_version":"Catalina","browserName":"Safari","browser_version":"13.0",'build':'BrowserStack - CORS test',// build name'name':'BStack-[NodeJS] Sample Test',// test name'browserstack.disableCorsRestrictions':'true'}asyncfunctionrunTestWithCaps(){let driver =newwebdriver.Builder().usingServer(`https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub`).withCapabilities(capabilities).build();try{await driver.get("https://polar-inlet-22085.herokuapp.com/");await driver.wait(webdriver.until.titleMatches(/CORS test/i),10000);// wait for 5 seconds for the web page to load completelyawaitnewPromise(resolve=>setTimeout(resolve,5000));//print screenshot of the web page in the 'Text Logs' section on your Automate session dashboardawait driver.takeScreenshot();}catch( e ){
console.log("Error:", e.message)}await driver.quit();}runTestWithCaps();
sing System;usingSystem.Threading;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Support.UI;namespaceSeleniumTest{publicclassScreenShotRemoteWebDriver:RemoteWebDriver,ITakesScreenshot{publicScreenShotRemoteWebDriver(Uri uri,OpenQA.Selenium.Safari.SafariOptions dc):base(uri, dc){}publicnewScreenshotGetScreenshot(){Response screenshotResponse =this.Execute(DriverCommand.Screenshot,null);string base64 = screenshotResponse.Value.ToString();returnnewScreenshot(base64);}}classProgram{staticvoidMain(string[] args){ScreenShotRemoteWebDriver driver;SafariOptions capability =newSafariOptions();
capability.AddAdditionalCapability("os","OS X");
capability.AddAdditionalCapability("os_version","Catalina");
capability.AddAdditionalCapability("browser","Safari");
capability.AddAdditionalCapability("browser_version","13.0");
capability.AddAdditionalCapability("browserstack.disableCorsRestrictions","true");
capability.AddAdditionalCapability("build","BrowserStack - CORS test");
capability.AddAdditionalCapability("name","BStack-[C_sharp] Sample Test");// test name
capability.AddAdditionalCapability("browserstack.user","YOUR_USERNAME");
capability.AddAdditionalCapability("browserstack.key","YOUR_ACCESS_KEY");
driver =newScreenShotRemoteWebDriver(newUri("https://hub-cloud.browserstack.com/wd/hub/"), capability);try{
driver.Navigate().GoToUrl("https://polar-inlet-22085.herokuapp.com/");// wait for 10 seconds until the browser title matches 'CORS Tester'var wait =newWebDriverWait(driver,newTimeSpan(0,0,10));var element = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleIs("CORS Tester"));// wait for 5 seconds for the web page to load completely
Thread.Sleep(5000);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboardITakesScreenshot screenshotDriver = driver asITakesScreenshot;
screenshotDriver.GetScreenshot();}catch{
Console.WriteLine("Exception: Title did not match");}
driver.Quit();}}}
<?phprequire_once('vendor/autoload.php');useFacebook\WebDriver\Remote\RemoteWebDriver;useFacebook\WebDriver\WebDriverBy;useFacebook\WebDriver\WebDriverExpectedCondition;$caps=array("os"=>"OS X","os_version"=>"Catalina","browser"=>"Safari","browser_version"=>"13.0","browserstack.disableCorsRestrictions"=>"true","name"=>"BStack-[Php] Sample Test",// test name"build"=>"BrowserStack - CORS test"// build name);$driver=RemoteWebDriver::create("https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",$caps);try{$driver->get("https://polar-inlet-22085.herokuapp.com");$driver->wait(10)->until(WebDriverExpectedCondition::titleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelysleep(5);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard$driver->takeScreenshot();}catch(Exception$e){echo'Exception occured';}$driver->quit();?>
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
desired_cap ={"os":"OS X","os_version":"Catalina","browser":"Safari","browser_version":"13.0","build":"BrowserStack - CORS test",# build name"name":"BStack-[Python] Sample Test",# test name"browserstack.disableCorsRestrictions":"true"}
driver = webdriver.Remote(
command_executor='https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub',
desired_capabilities=desired_cap)try:
driver.get("https://polar-inlet-22085.herokuapp.com")
WebDriverWait(driver,10).until(EC.title_contains("CORS Tester"))# wait for 5 seconds for the web page to load completely
time.sleep(5)# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver.save_screenshot('screenshots.png')except:print("An exception occurred - Title did not match 'CORS Tester'")finally:
driver.quit()
require'rubygems'require'selenium-webdriver'# Input capabilities
caps =Selenium::WebDriver::Remote::Capabilities.new
caps['browser']='Safari'
caps['os_version']='Catalina'
caps['os']='OS X'
caps['browser_version']='13.0'
caps['browserstack.disableCorsRestrictions']='true'
caps['name']='BStack-[Ruby] Sample Test'# test name
caps['build']='BrowserStack - CORS test'# build name
driver =Selenium::WebDriver.for(:remote,:url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",:desired_capabilities=> caps)begin
driver.navigate.to "https://polar-inlet-22085.herokuapp.com"
wait =Selenium::WebDriver::Wait.new(:timeout=>10)# seconds
wait.until{!driver.title.match(/CORS Tester/i).nil?}# wait for 5 seconds for the web page to load completely
sleep 5# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
driver.save_screenshot("screenshots.png")rescue
puts "Exception occured"end
driver.quit
After you run the test script, a screenshot of the web page is displayed in the Text Logs section of your Automate session dashboard, as shown in the following image: