Is it possible to check on how many Safari windows are active?

I want to create a macro that does one thing if there are two or more safari windows and another if there is only one Safari window.

I found this online but not really sure how to utilise it to make it work for my case.

Thank you for your help.

This script by Chris (@ccstone) should do the trick.

###AppleScript to Get Number of Safari Windows
Per Chris, this has been adapted to work with the latest version of macOS Sierra. From my testing, it also works on Safari 10.1 (11603.1.30.0.34) on macOS 10.11.6.

------------------------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2017/04/30 23:01
# dMod: 2017/04/30 23:17
# Appl: Safari
# Task: List all valid document windows.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Safari, @List, @Valid, @Document, @Windows
# Note: Due to problems in Safari 10.1 on macOS 10.12.4.
------------------------------------------------------------------------------

tell application "Safari"
  set winList to current tab of windows
  try
    winList / 0
  on error e
    set AppleScript's text item delimiters to {"window id ", " of "}
    set winList to text items of e
  end try
  repeat with i in winList
    try
      if (contents of i) ≠ "" then
        set (contents of i) to (contents of i) as integer
      end if
    end try
  end repeat
  set winList to integers of winList
  repeat with i in winList
    set contents of i to window id (contents of i)
  end repeat
  
  set numWin to count of winList
  
end tell

return numWin
1 Like

@ccstone has everything it seems. Thank you a lot Michael.

Here is the macro I made using this. It just increases playback on another window for faster viewing.

###MACRO:   a: increase playback on youtube

~~~ VER: 1.0    2017-05-03 ~~~

####DOWNLOAD:
a- increase playback on youtube.kmmacros (32 KB)


###ReleaseNotes

TBD


Hey Guys,

If you just want the number of document windows then you can pare that down to this:

------------------------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2017/05/02 22:30
# dMod: 2017/05/02 22:33
# Appl: Safari
# Task: Get number of valid Safari Document Windows.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Safari, @Number, @Valid, @Safari, @Document, @Windows
------------------------------------------------------------------------------

tell application "Safari"
   set numberOfSafariWindows to length of (get current tab of windows)
end tell

------------------------------------------------------------------------------

-Chris