Search code examples
applescript

Get window of certain tab in Applescript


So I'm trying to set the variable called theWindow to a window with a tab whose URL contains "google.com".

tell application "Google Chrome"
    set theTabs to a reference to (tabs of windows whose URL contains "google.com")
    set theTab to item 1 of theTabs
    set theWindow to window of theTab
end tell

However, this doesn't work and the code returns:

Google Chrome got an error: Can’t get window of tab id 384 of window id 383." number -1728 from window of tab id 384 of window id 383

Solution

  • I don't use Chrome so you may have to convert but this is how it might be done with Safari.

        tell application "Safari"
            set sst to "google.com"
            
            repeat with w in windows
                if exists (tabs of w whose URL contains sst) then
                    set wix to index of w
                    set wid to id of w
                    set theWindow to window id wid
                    exit repeat
                end if
            end repeat
        end tell
    
        try
            display dialog "Window: " & wix & return & "Window ID: " & wid
        end try
    

    It cycles through open windows and checks if any of its tabs have a matching URL. If at least one does, then it provides the index and ID for that window. Obviously, if multiple tabs match the search term then the result will be affected.