Search code examples
macostabssafariapplescript

How to close safari tabs by url using applescript


I'm looking for a way to close specific tabs in safari by the url. I would probably expand on something like this:

tell application "Safari"
    repeat with t in tabs of windows
        tell t
            if name starts with "google.com" then close
        end tell
    end repeat
end tell

the problem here is that i haven't found a way how to get the url value of a tab and close them based on that.


Solution

  • You can get the URL from Safari based on the active tab.

    tell application "Safari"
        set w to first window
        set t to current tab of w
        display dialog (URL of t as string)
    end tell
    

    And then you could iterate over every tab/page like this :

    tell application "Safari"
        set windowCount to number of windows
            repeat with x from 1 to windowCount
                set tabCount to number of tabs in window x
                repeat with y from 1 to tabCount
                    set thistab to tab y of window x
                    set foo to URL of thistab
                    if foo is not equal to "bar" then close thistab
               end repeat
           end repeat
    end tell