MACRO or PLUGIN: Open or Refresh a URL in a Tab (Safari & Chrome)

Hey Nikita,

Easily fixed – search the script for “new”.

-Chris

------------------------------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2017/01/06 19:04
# dMod: 2017/03/06 17:40
# Appl: Safari
# Task: Serially switch between tabs having the same domain (or other filter text in the URL) in the front window.
#     : 2017/03/06 – Now opens a new tab if the urlFilterText isn't found.
# Libs: None
# Osax: None
# Tags: @Applescript, @Script, @Safari, @Serially, @Switch, @Tabs, @Domain, @Filter, @Front, @Window
# Vers: 2.0
------------------------------------------------------------------------------

set urlFilterText to "forum.keyboardmaestro.com"
set urlToFetch to "https://forum.keyboardmaestro.com"

tell application "Safari"
   tell front window
      set filteredTabIndexList to index of tabs where its URL contains urlFilterText
      set currentTabIndex to index of current tab
      
      if filteredTabIndexList = {} then -- New
         
         set tabURL to URL of current tab
         
         try

            tabURL -- will be undefined if the page is blank and throw an error

            # If the above line does NOT error:
            make new tab at end of tabs with properties {URL:urlToFetch}
            set current tab to last tab

         on error

            # Tab is blank, so we'll just use it.
            set its current tab's URL to urlToFetch

         end try
         
         return
         
      end if
      
      if currentTabIndex is in filteredTabIndexList and currentTabIndex ≠ (last item of filteredTabIndexList) then
         set listItemOffset to getListItemOffset(filteredTabIndexList, currentTabIndex) of me
         set current tab to tab (item (listItemOffset + 1) of filteredTabIndexList)
      else
         set current tab to tab (item 1 of filteredTabIndexList)
      end if
      
   end tell
end tell

------------------------------------------------------------------------------
--» HANDLERS
------------------------------------------------------------------------------
on getListItemOffset(theList, listItemValue)
   if listItemValue is not in theList then error "getListItemOffset():  “listItemValue” is not in “theList”!"
   repeat with listItemNum from 1 to (length of theList)
      if (item listItemNum of theList) = listItemValue then
         return listItemNum
      end if
   end repeat
end getListItemOffset
------------------------------------------------------------------------------
2 Likes