Toggle Night Shift

Two quick notes on this AppleScript:

  1. The System Preference pane objects contain a set of anchors, which includes any tabs that sit at the top of the preference pane. In this case, there are three of them. Instead of asking System Events to click radio button 3 of tab group 1 of window 1, you can get System Preferences to

    reveal the anchor named "displaysNightShiftTab" of the current pane
    
  2. The best thing about System Preferences is that it doesn't need to be active or visible in order to have its UI scripted through System Events. Currently, telling it to activate brings it into focus, where the user can see the window change pane, then change tab, then the checkbox ticked or unticked. For a more seamless, background experience, remove that command.

Here's what the resulting final script might look like:

tell application "System Preferences" to reveal the ¬
	anchor named "displaysNightShiftTab" of ¬
	pane id "com.apple.preference.displays"

tell application "System Events" to tell ¬
	process "System Preferences" to tell ¬
	window 1 to tell ¬
	tab group 1 to tell ¬
	checkbox "Turn On Until Later Today" to ¬
	perform action "AXPress"

quit application "System Preferences"

In this version, the user never sees a single glimpse of the System Preferences window, but only the desired effect of initiating or terminating Night Shift.


Note: checkbox 1 is probably preferable for portability, as non-English systems won't understand checkbox "Turn On Until Later Today".
4 Likes