How do I scroll to the top of a window using applescript?

后端 未结 3 2105
不知归路
不知归路 2021-01-02 21:00

I want applescript to scroll a window all the way up.

I\'ve tried the page up key, the home key, and I\'ve tried looking for a way to scroll using the built in scro

3条回答
  •  囚心锁ツ
    2021-01-02 21:32

    The alternative to sending keystrokes is to use GUI scripting.

    Caveat: While GUI scripting is more robust than sending keystrokes for a given version of an application, changes in the application's layout in future versions can break your code.

    Also:

    • GUI scripting requires that access for assistive devices be enabled; enabling requires admin privileges:

      • up to 10.8, this could be done programmatically, system-wide by executing tell application "System Events" to set UI elements enabled to true (required admin privileges)
      • Sadly, on 10.9+, this no longer works, and apps must be authorized manually, individually - the system will prompt you on first run (requires admin privileges)
      • however, in both scenarios tell application "System Events" to get UI elements enabled will report whether access is enabled or not.
    • Determining the right UI element targets can be non-trivial and tedious; using the Accessibility Inspector utility that comes with Xcode helps. The class names reported by this utility correspond to the UI element classes contained in the System Events dictionary; e.g., AXSplitGroup corresponds to splitter group.

    The following scrolls Safari 6.0.3's front window to the top (access for assistive devices must be enabled):

    tell application "System Events"
    
        # Use Accessibility Inspector to find the desired target.
        tell front window of process "Safari"
            tell scroll bar 1 of scroll area 1 of group 1 of group 1 of last group
                set value of attribute "AXValue" to 0  # Scroll to top.
            end tell
        end tell
    
    end tell
    

    Update: As a reminder that this type of scripting works well for a given version of an application, the code had to be changed for Safari 8.0.4:

    tell application "System Events"
    
        # Use Accessibility Inspector to find the desired target.
        tell front window of process "Safari"
            tell scroll bar 1 of scroll area 1 of group 1 of group 1 of group 2
                set value of attribute "AXValue" to 0  # Scroll to top.
            end tell
        end tell
    
    end tell
    

提交回复
热议问题