Search code examples
c#selenium-webdriversafariremotewebdriver

How do I add options to Safari options and remote webdriver


This options are added to our Chromium Driver for use with Chrome and Edge

options.AddUserProfilePreference("download.default_directory", DownloadPath);

We are now branching out into Mac/Safari and so using SafariOptions and RemoteWebDriver which do not like the option syntax above. Can anyone show me how to achieve this in Safari please.

We use Selenium and C#


Solution

  • In Safari, Selenium does not provide a direct way to set the download directory like in Chrome or Edge because Safari has stricter security constraints. However, you can manually configure Safari’s settings to allow automatic downloads.

    Steps to Handle File Downloads in Safari using Selenium (C#)

    1. Manually enable auto-downloads:

      • Open Safari.
      • Go to PreferencesWebsitesDownloads.
      • Set it to "Allow" for the relevant domains.
    2. Use SafariOptions with RemoteWebDriver:

      using OpenQA.Selenium;
      using OpenQA.Selenium.Safari;
      using OpenQA.Selenium.Remote;
      
      class Program
      {
          static void Main()
          {
              SafariOptions options = new SafariOptions();
      
              // Initialize RemoteWebDriver with SafariOptions
              IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options);
      
              driver.Navigate().GoToUrl("https://example.com");
      
              // Find and click the download button (adjust selector as needed)
              driver.FindElement(By.Id("downloadButton")).Click();
      
              // Wait or verify download (custom logic needed)
          }
      }
      
    3. Alternative Workarounds:

      • Use AppleScript or a browser extension to automate the download process.
      • Monitor the ~/Downloads/ folder to check for the file.

    Unlike Chromium-based browsers, Safari’s WebDriver implementation does not allow programmatic changes to download settings due to security restrictions.