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{WebDriverdriver=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 dashboarddriver=(RemoteWebDriver)newAugmenter().augment(driver);((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);}catch(Exceptione){// print any exception in the IDE's consoleSystem.out.println(e);}driver.quit();}}
constwebdriver=require('selenium-webdriver');asyncfunctionrunTestWithCaps(){try{awaitdriver.get("https://polar-inlet-22085.herokuapp.com/");awaitdriver.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 dashboardawaitdriver.takeScreenshot();}catch(e){console.log("Error:",e.message)}awaitdriver.quit();}runTestWithCaps();
singSystem;usingSystem.Threading;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Support.UI;namespaceSeleniumTest{publicclassScreenShotRemoteWebDriver:RemoteWebDriver,ITakesScreenshot{publicScreenShotRemoteWebDriver(Uriuri,OpenQA.Selenium.Safari.SafariOptionsdc):base(uri,dc)publicnewScreenshotGetScreenshot(){ResponsescreenshotResponse=this.Execute(DriverCommand.Screenshot,null);stringbase64=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'varwait=newWebDriverWait(driver,newTimeSpan(0,0,10));varelement=wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelyThread.Sleep(5000);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboardITakesScreenshotscreenshotDriver=driverasITakesScreenshot;screenshotDriver.GetScreenshot();}catch{Console.WriteLine("Exception: Title did not match");}driver.Quit();}}}
fromseleniumimportwebdriverfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasECimporttimetry: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{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_ACCESS_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_ACCESS_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescapabilities=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);WebDriverdriver=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 dashboarddriver=(RemoteWebDriver)newAugmenter().augment(driver);((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);}catch(Exceptione){// print any exception in the IDE's consoleSystem.out.println(e);}driver.quit();}}
constwebdriver=require('selenium-webdriver');// Input capabilitiesconstcapabilities={'bstack:options':{"os":"OS X","osVersion":"Monterey","projectName":"BrowserStack - CORS test","buildName":"BStack Sample Test","disableCorsRestrictions":"true",},"browserName":"Safari","browserVersion":"15.0",}asyncfunctionrunTestWithCaps(){letdriver=newwebdriver.Builder().usingServer(`https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub`).withCapabilities(capabilities).build();try{awaitdriver.get("https://polar-inlet-22085.herokuapp.com/");awaitdriver.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 dashboardawaitdriver.takeScreenshot();}catch(e){console.log("Error:",e.message)}awaitdriver.quit();}runTestWithCaps();
singSystem;usingSystem.Threading;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Support.UI;namespaceSeleniumTest{publicclassScreenShotRemoteWebDriver:RemoteWebDriver,ITakesScreenshot{publicScreenShotRemoteWebDriver(Uriuri,OpenQA.Selenium.Safari.SafariOptionsdc):base(uri,dc){}publicnewScreenshotGetScreenshot(){ResponsescreenshotResponse=this.Execute(DriverCommand.Screenshot,null);stringbase64=screenshotResponse.Value.ToString();returnnewScreenshot(base64);}}classProgram{staticvoidMain(string[]args){ScreenShotRemoteWebDriverdriver;SafariOptionscapabilities=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'varwait=newWebDriverWait(driver,newTimeSpan(0,0,10));varelement=wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelyThread.Sleep(5000);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboardITakesScreenshotscreenshotDriver=driverasITakesScreenshot;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 occurred';}$driver->quit();?>
fromseleniumimportwebdriverfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasECimporttimedesired_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 capabilitiescapabilities={'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)begindriver.navigate.to"https://polar-inlet-22085.herokuapp.com"wait=Selenium::WebDriver::Wait.new(:timeout=>10)# secondswait.until{!driver.title.match(/CORS Tester/i).nil?}# wait for 5 seconds for the web page to load completelysleep5# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboarddriver.save_screenshot("screenshots.png")rescueputs"Exception occurred"enddriver.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{publicstaticfinalStringAUTOMATE_USERNAME="YOUR_USERNAME";publicstaticfinalStringAUTOMATE_ACCESS_KEY="YOUR_ACCESS_KEY";publicstaticfinalStringURL="https://"+AUTOMATE_USERNAME+":"+AUTOMATE_ACCESS_KEY+"@hub-cloud.browserstack.com/wd/hub";publicstaticvoidmain(String[]args)throwsException{DesiredCapabilitiescaps=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 namecaps.setCapability("build","BrowserStack - CORS test");// CI/CD job or build namecaps.setCapability("browserstack.disableCorsRestrictions","true");WebDriverdriver=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 dashboarddriver=(RemoteWebDriver)newAugmenter().augment(driver);((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);}catch(Exceptione){// print any exception in the IDE's consoleSystem.out.println(e);}driver.quit();}}
constwebdriver=require('selenium-webdriver');// Input capabilitiesconstcapabilities={"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(){letdriver=newwebdriver.Builder().usingServer(`https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub`).withCapabilities(capabilities).build();try{awaitdriver.get("https://polar-inlet-22085.herokuapp.com/");awaitdriver.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 dashboardawaitdriver.takeScreenshot();}catch(e){console.log("Error:",e.message)}awaitdriver.quit();}runTestWithCaps();
singSystem;usingSystem.Threading;usingOpenQA.Selenium;usingOpenQA.Selenium.Remote;usingOpenQA.Selenium.Safari;usingOpenQA.Selenium.Support.UI;namespaceSeleniumTest{publicclassScreenShotRemoteWebDriver:RemoteWebDriver,ITakesScreenshot{publicScreenShotRemoteWebDriver(Uriuri,OpenQA.Selenium.Safari.SafariOptionsdc):base(uri,dc){}publicnewScreenshotGetScreenshot(){ResponsescreenshotResponse=this.Execute(DriverCommand.Screenshot,null);stringbase64=screenshotResponse.Value.ToString();returnnewScreenshot(base64);}}classProgram{staticvoidMain(string[]args){ScreenShotRemoteWebDriverdriver;SafariOptionscapability=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 namecapability.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'varwait=newWebDriverWait(driver,newTimeSpan(0,0,10));varelement=wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.TitleIs("CORS Tester"));// wait for 5 seconds for the web page to load completelyThread.Sleep(5000);// print screenshot of the web page in the 'Text Logs' section of your Automate session dashboardITakesScreenshotscreenshotDriver=driverasITakesScreenshot;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 occurred';}$driver->quit();?>
fromseleniumimportwebdriverfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.supportimportexpected_conditionsasECimporttimedesired_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 capabilitiescaps=Selenium::WebDriver::Remote::Capabilities.newcaps['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 namecaps['build']='BrowserStack - CORS test'# build namedriver=Selenium::WebDriver.for(:remote,:url=>"https://YOUR_USERNAME:YOUR_ACCESS_KEY@hub-cloud.browserstack.com/wd/hub",:desired_capabilities=>caps)begindriver.navigate.to"https://polar-inlet-22085.herokuapp.com"wait=Selenium::WebDriver::Wait.new(:timeout=>10)# secondswait.until{!driver.title.match(/CORS Tester/i).nil?}# wait for 5 seconds for the web page to load completelysleep5# print screenshot of the web page in the 'Text Logs' section of your Automate session dashboarddriver.save_screenshot("screenshots.png")rescueputs"Exception occurred"enddriver.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: