Search code examples
buttonsafariapplescripttoolbarsafari-extension

How to click a Safari toolbar Extension button using AppleScript (when in full screen)


I'm trying to write a small AppleScript which will click the OneNote toolbar Extension, so I can bind it to a keyboard shortcut. The script below works perfectly as long as the instance of Safari is in windowed mode, but in full screen it fails and returns the error:

error "System Events got an error: Can’t get window 1 of process \"Safari\". Invalid index." number -1719 from window 1 of process "Safari"

I have exported this script as an application and granted accessibility access to it. Effectively it seems as though a full screen Safari window is not given an index or is no longer a window and is now a different object.

tell application "System Events"
 tell process "Safari"
    click button whose description contains "OneNote" of toolbar 1 of window 1
 end tell 
end tell

MacBook Pro (Retina, 13-inch, Late 2013) OS X El Capitan, Version: 10.11.6 (15G1004)


Solution

  • try this script. It works whether Safari is in full screen mode or not:

    set myButton to "OneNote"
    
    tell application "System Events"
        tell process "Safari"
            set isfullscreen to value of attribute "AXFullScreen" of window 1
            if isfullscreen is true then
                click ((buttons of toolbar 1 of group 1 of window 1) whose description contains myButton)
            else
                click ((buttons of toolbar 1 of window 1) whose description contains myButton)
            end if
        end tell
    end tell
    

    Replace "OneNote" with any button you'd like to click.