MacOS – Open an URL in Safari with Private Browsing

command linemacossafari

I want to open an URL in a browser's private mode.
--args -incognito does the job with Chromium-based browsers (e.g. open -na "Google Chrome" --args -incognito http://www.example.com).
I tried -incognito, -private, -private-browsing arguments, but none worked with Safari.
What's a Safari's command option to open in private mode?

Best Answer

Safari does not have similar command line options like Google Chrome, however, here is a way to roll your own:

In Terminal, run the following compound command:

touch safari; open -e safari; chmod +x safari

Copy and paste the example AppleScript code, shown further below, into the opened safari document, then save it.

You should then move the safari shell script to a directory located within the shell's PATH.

I moved it to /usr/local/bin, e.g,:

sudo mv -v safari /usr/local/bin/

Now from Terminal I can open a new private window for Safari.
Typing just the executable's name without any arguments shows how it can be used e.g,:

% safari
Missing Arguments!...
Examples:
safari https://www.example.com
safari -private
safari -private https://www.example.com
%    

Notes:

  • As coded, the example AppleScript code is focused on opening a new private window, however, as you can see it can open a normal new window to the provided URL too. For the new private window, you can open it with or without passing it a URL.
  • As coded, the example AppleScript code only allow for one URL to be passed at a time. Additional coding is required to allow passing multiple URLs.

Example AppleScript code:

#!/usr/bin/osascript

on run args
    
    if args is {} then return ¬
        "Missing Arguments!..." & linefeed & ¬
        "Examples:" & linefeed & ¬
        "safari https://www.example.com" & linefeed & ¬
        "safari -private" & linefeed & ¬
        "safari -private https://www.example.com"       
    
    set newPrivateWindow to false
    
    if item 1 of args contains "-private" then
        set newPrivateWindow to true
        if (length of args) is not greater than 1 then
            set theURL to missing value
        else
            set theURL to item 2 of args
        end
    else
        set the theURL to item 1 of args
    end if
    
    tell application "Safari" to activate
    delay 1
    
    if newPrivateWindow then
        tell application "System Events" to ¬
            keystroke "n" using ¬
                {shift down, command down}
        delay 1
        openURL(theURL)
    else
        tell application "System Events" to ¬
            keystroke "n" using ¬
                {command down}
        delay 1
        openURL(theURL)
    end if
    
end run

on openURL(theURL)
    if theURL is missing value then
        return
    else
        tell application "Safari" to ¬
            set URL of ¬
                current tab of ¬
                front window to ¬
                theURL as string
    end if
end openURL