AppleScript to change default web browser

applescriptgoogle-chrome

I want to be able to change the default web browser of my Mac to Google Chrome using AppleScript. Here is my idea:

set result to button returned of (display dialog "Would you like to change to Chrome?")
if result = "OK" then
    do shell script ("open -a 'Google Chrome' --args --make-default-browser")
else
    display dialog "No change in the default web browser"
end if

However, I always get this window popping up that I cannot programmatically deal with for some reason. I want to select "Use Chrome".

Pop-up screenshot

I know of a few manual ways of changing it, such as in the 'General' tab of the System Preferences but I need something reliable such as this shell command.
How do I accomplish the above via AppleScript?

Best Answer

You can deal with the confirmation window via UI scripting. This will press the “Use” button:

try
  tell application "System Events"
    tell application process "CoreServicesUIAgent"
      tell window 1
        tell (first button whose name starts with "use")
          perform action "AXPress"
        end tell
      end tell
    end tell
  end tell
end try

Source