MacOS – How to find the application that controls system dialog window

applescriptautomatormacossystem-prefs

I am trying to change the default browser between Chrome and Safari without needing user input except for initially running it.

I found this utility that takes care of the difficult bit:

It can be installed using Homebrew by running:

brew defaultbrowser

However when you run it a dialogue box shows up asking if I want to change browser. I want to press the "Yes "button using AppleScript. Below is a screenshot.

screenshot that comes up when you call <code>default browser</code>

I want to find the application that contains this window. Is there a better way to find out where the window is rather than go through them all?

I've tried foremost window but it seems to return the foremost program. Here's some program I've tried:

tell application "System Events"
        tell process "SecurityAgent"
            click button 1 of window 1
        end tell
        delay 0.2
end tell

Best Answer

When you have a window that is a system dialog, or alert, type of window, and you do not know which application it belongs to, you can try using code such as the following example AppleScript code to determine the name of the application to which it belongs:

tell application "System Events" to ¬
    get name of every application process ¬
        whose role description of window 1 is "system dialog"

Or:

tell application "System Events" to ¬
    get name of every application process ¬
        whose accessibility description of window 1 is "alert"

That said, the application process you want System Events to interact with is: CoreServicesUIAgent

For example, if Google Chrome is my default browser and I run, e.g.:

do shell script "/usr/local/bin/defaultbrowser 'safari'"

Then this dialog box appears:

enter image description here

To click the Use “Safari” button, use:

tell application "System Events" to ¬
    click button "Use “Safari”" of ¬
        window 1 of application process "CoreServicesUIAgent"

Note: You can also use click button 1 instead of click button "Use “Safari”".

Obviously you'll need to adjust for your particular needs/wants, but you now have the application process that System Events needs to interact with.