Actually, the script works fine in my testing with Safari 11.1.1 (12605.2.8) on macOS 10.12.6.
But it does require that you properly set the KM Variable URLToFind to the full URL of an existing tab in one of the Safari windows.
My script does exactly that. It sets the Safari Window frontmost which has a tab with the specified URL.
It does exactly as you asked in your OP:
Here's a macro with the enhanced script embedded.
You will need to change the first Action to be the URL of an existing tab, whose window you want to make frontmost.
MACRO: Bring Safari Window with URL to Front [Example]
~~~ VER: 1.0 2018-06-22 ~~~
Bring Safari Window with URL to Front [Example].kmmacros (3.8 KB)
Note: This Macro was uploaded in a DISABLED state. You must enable before it can be triggered.
AppleScript to Make Safari Window FrontMost with URL
property ptyScriptName : "Make Safari Window with URL FrontMost"
property ptyScriptVer : "1.1"
property ptyScriptDate : "2018-06-22"
property ptyScriptAuthor : "JMichaelTX"
tell application "Keyboard Maestro Engine" to set urlToFind to getvariable "URLToFind"
--set urlToFind to "https://wiki.keyboardmaestro.com/doku.php"
set scriptResults to "Sorry, could NOT find any tab in any window with this URL" & linefeed & urlToFind
tell application "Safari"
set winList to windows
set winTitle to ""
repeat with oWin in winList
set oTab to (first tab whose URL is urlToFind)
set index of oWin to 1
set winID to id
set winTitle to name
set current tab to oTab
set scriptResults to "Window with tab URL found and set frontmost:" & linefeed & urlToFind
tell application "Safari" to set oWin to front
if (winTitle ≠ "") then
tell application "System Events"
tell application process "Safari"
set oWin2 to first window whose name is winTitle
set focused of oWin2 to true
tell oWin2 to perform action "AXRaise"
Questions, comments, issues, suggestions?