Skip to main content
Get Automate insights in Microsoft Teams with our new integration! Get Started!.

Disable CORS restriction

A guide to disabling CORS restriction for running tests on Safari browsers in BrowserStack Automate.

In this guide, you will learn:

Overview

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.

Note: Disabling CORS restriction may cause security issues in your website under test. Use this capability only after careful consideration.

Supported versions

The following table provides a list of supported browsers and OS platforms where you can use the disableCorsRestrictions capability.

Browser/OS Supported versions
Safari browser v12 and above
macOS platform Monterey, Big Sur, Catalina, and Mojave

The following table provides a list of supported browsers and OS platforms where you can use the browserstack.disableCorsRestrictions capability.

Browser/OS Supported versions
Safari browser v12 and above
macOS platform Monterey, Big Sur, Catalina, and Mojave

Set the capability

Use the following sample code snippets to set the disableCorsRestrictions capability to true in your test script:

DesiredCapabilities capabilities = new DesiredCapabilities();
HashMap<String, Object> browserstackOptions = new HashMap<String, Object>();
browserstackOptions.put("disableCorsRestrictions", "true");
capabilities.setCapability("bstack:options", browserstackOptions);
var capabilities = {
	'bstack:options' : {
		"disableCorsRestrictions" : "true",
	},
}
SafariOptions capabilities = new SafariOptions();
browserstackOptions.Add("disableCorsRestrictions", "true");
capabilities.AddAdditionalOption("bstack:options", browserstackOptions);
$caps = array(
	'bstack:options' => array(
		"disableCorsRestrictions" => "true",
	),
)
desired_cap = {
	'bstack:options' : {
		"disableCorsRestrictions" : "true",
	},
}
capabilities = {
	'bstack:options' => {
		"disableCorsRestrictions" => "true",
	},
}

The following table provides information about the disableCorsRestrictions capability:

Capability Description Expected values
disableCorsRestrictions Disable CORS restrictions in the Safari browser, which is enabled by default. true: Disables CORS restriction
false(default): Enables CORS restriction

Use the following sample code snippets to set the browserstack.disableCorsRestrictions capability to true in your test script:

DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability("browserstack.disableCorsRestrictions", "true");
var capabilities = {
 "browserstack.disableCorsRestrictions" : "true"
}
OpenQA.Selenium.Safari.SafariOptions safariCapability = new OpenQA.Selenium.Safari.SafariOptions();
safariCapability.AddAdditionalCapability("browserstack.disableCorsRestrictions", "true");
$caps = array(
 "browserstack.disableCorsRestrictions" => "true"
);
capabilities = {
 "browserstack.disableCorsRestrictions": "true"
}
caps = Selenium::WebDriver::Remote::Capabilities.new
caps["browserstack.disableCorsRestrictions"] = "true"

The following table provides information about the browserstack.disableCorsRestrictions capability:

Capability Description Expected values
browserstack.disableCorsRestrictions Disable CORS restrictions in the Safari browser, which is enabled by default. true: Disables CORS restriction
false(default): Enables CORS restriction

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:

Due to CORS restriction, https://polar-inlet-22085.herokuapp.com fails to fetch content from another domain on its page.

With CORS restriction

After the CORS restrictions are disabled, https://polar-inlet-22085.herokuapp.com is able to fetch content from another domain.

Without CORS restriction

Example test script

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:


import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.OutputType;
import java.util.concurrent.TimeUnit;
import java.net.URL;
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class JavaSample {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_ACCESS_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_ACCESS_KEY + "@hub-cloud.browserstack.com/wd/hub";
  public static void main(String[] args) throws Exception {
  DesiredCapabilities capabilities = new DesiredCapabilities();
  capabilities.setCapability("browserName", "Safari");
  capabilities.setCapability("browserVersion", "15.0");
  HashMap<String, Object> browserstackOptions = new HashMap<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 = new RemoteWebDriver(new URL(URL), caps);
    try {
      driver.get("https://polar-inlet-22085.herokuapp.com/");
      new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.titleIs("CORS Tester"));
      // wait for 5 seconds for the web page to load completely
      TimeUnit.SECONDS.sleep(5);
      // print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
      driver = (RemoteWebDriver) new Augmenter().augment(driver);
	    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    }
    catch (Exception e){
      // print any exception in the IDE's console
      System.out.println(e);
    }
  driver.quit();
  }
}

const webdriver = require('selenium-webdriver');

// Input capabilities
const capabilities = {
	'bstack:options' : {
		"os" : "OS X",
		"osVersion" : "Monterey",
		"projectName" : "BrowserStack - CORS test",
		"buildName" : "BStack Sample Test",
		"disableCorsRestrictions" : "true",
	},
	"browserName" : "Safari",
	"browserVersion" : "15.0",
}

async function runTestWithCaps () {
  let driver = new webdriver.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 completely
    await new Promise(resolve => setTimeout(resolve, 5000));
    //print screenshot of the web page in the 'Text Logs' section on your Automate session dashboard
    await driver.takeScreenshot();
  }
catch ( e ) {
  console.log("Error:", e.message)
}
await driver.quit();
}
runTestWithCaps();

sing System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTest
{
  public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
  {
    public ScreenShotRemoteWebDriver(Uri uri, OpenQA.Selenium.Safari.SafariOptions dc)
      : base(uri, dc)
    {
    }

    public new Screenshot GetScreenshot()
    {
      Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
      string base64 = screenshotResponse.Value.ToString();
      return new Screenshot(base64);
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      ScreenShotRemoteWebDriver driver;
      SafariOptions capabilities = new SafariOptions();
      capabilities.BrowserVersion = "15.0";
      Dictionary<string, object> browserstackOptions = new Dictionary<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 = new ScreenShotRemoteWebDriver(new Uri("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 = new WebDriverWait(driver, new TimeSpan(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 dashboard
        ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
        screenshotDriver.GetScreenshot();
      }
      catch
      {
        Console.WriteLine("Exception: Title did not match");
      }
      driver.Quit();
    }
  }
}

<?php
require_once('vendor/autoload.php');
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\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 completely
    sleep(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


import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.OutputType;
import java.util.concurrent.TimeUnit;
import java.net.URL;
import java.time.Duration;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class JavaSample {
  public static final String AUTOMATE_USERNAME = "YOUR_USERNAME";
  public static final String AUTOMATE_ACCESS_KEY = "YOUR_ACCESS_KEY";
  public static final String URL = "https://" + AUTOMATE_USERNAME + ":" + AUTOMATE_ACCESS_KEY + "@hub-cloud.browserstack.com/wd/hub";
  public static void main(String[] args) throws Exception {
    DesiredCapabilities caps = new DesiredCapabilities();
    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 = new RemoteWebDriver(new URL(URL), caps);
    try {
      driver.get("https://polar-inlet-22085.herokuapp.com/");
      new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.titleIs("CORS Tester"));
      // wait for 5 seconds for the web page to load completely
      TimeUnit.SECONDS.sleep(5);
      // print screenshot of the web page in the 'Text Logs' section of your Automate session dashboard
      driver = (RemoteWebDriver) new Augmenter().augment(driver);
	    ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    }
    catch (Exception e){
      // print any exception in the IDE's console
      System.out.println(e);
    }
  driver.quit();
  }
}

const webdriver = require('selenium-webdriver');

// Input capabilities
const 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'
}
async function runTestWithCaps () {
  let driver = new webdriver.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 completely
    await new Promise(resolve => setTimeout(resolve, 5000));
    //print screenshot of the web page in the 'Text Logs' section on your Automate session dashboard
    await driver.takeScreenshot();
  }
catch ( e ) {
  console.log("Error:", e.message)
}
await driver.quit();
}
runTestWithCaps();

sing System;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Remote;
using OpenQA.Selenium.Safari;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTest
{
  public class ScreenShotRemoteWebDriver : RemoteWebDriver, ITakesScreenshot
  {
    public ScreenShotRemoteWebDriver(Uri uri, OpenQA.Selenium.Safari.SafariOptions dc)
      : base(uri, dc)
    {
    }

    public new Screenshot GetScreenshot()
    {
      Response screenshotResponse = this.Execute(DriverCommand.Screenshot, null);
      string base64 = screenshotResponse.Value.ToString();
      return new Screenshot(base64);
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
      ScreenShotRemoteWebDriver driver;
      SafariOptions capability = new SafariOptions();
      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 = new ScreenShotRemoteWebDriver(new Uri("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 = new WebDriverWait(driver, new TimeSpan(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 dashboard
        ITakesScreenshot screenshotDriver = driver as ITakesScreenshot;
        screenshotDriver.GetScreenshot();
      }
      catch
      {
        Console.WriteLine("Exception: Title did not match");
      }
      driver.Quit();
    }
  }
}

<?php
require_once('vendor/autoload.php');
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Facebook\WebDriver\WebDriverBy;
use Facebook\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 completely
    sleep(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:

CORS session view

Need some help?

If you need any help, contact our Support team.

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