有没有办法使用 RemoteWebDriver for SauceLabs 禁用 CORS 检查

Is there way to disable CORS check using RemoteWebDriver for SauceLabs

问题说明了一切,我正在尝试在 SauceLabs 上执行一些 selenium 测试,该测试加载了一个发出跨域请求的网页。我在想有没有办法通过代码以独立于平台的方式禁用 CORS。

当使用 ChromeDriver / Chrome 组合来禁用 检查你可以使用 --disable-web-security 参数。

content_switches.cc中定义为:

// Don't enforce the same-origin policy. (Used by people testing their sites.)
const char kDisableWebSecurity[]            = "disable-web-security";

代码示例:

  • Windows:

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--disable-web-security"); // don't enforce the same-origin policy
    options.addArguments("--disable-gpu"); // applicable to windows os only
    options.addArguments("--user-data-dir=~/chromeTemp"); // applicable to windows os only
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://google.com");
    
  • OSX:

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--disable-web-security"); // don't enforce the same-origin policy
    options.addArguments("--user-data-dir=/tmp/chrome_dev_test");
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://google.com");
    
  • Linux

    ChromeOptions options = new ChromeOptions();
    options.addArguments("--disable-web-security"); // don't enforce the same-origin policy
    WebDriver driver = new ChromeDriver(options);
    driver.get("https://google.com");
    

Note: If you need access to local files for development/testing purposes like AJAX or JSON, you can use -–allow-file-access-from-files flag.


参考资料


结尾

您可以在以下位置找到一些相关讨论:

  • Error: Permission denied to access property “x” due to same/cross origin policy using Selenium?