Display currently playing in Youtube + Switching to youtube window on click

Hi everyone,

As a beginner I've made some scripts to display what's playing on youtube plus another script to switch to the youtube window.
Feel free to criticise my work so that I can improve :upside_down_face:.

Currently playing script :

set str to "" as string
if ((str is equal to str) and (application "Safari" is running)) then
	tell application "Safari"
		repeat with t in tabs of windows
			tell t
				if URL starts with "https://www.youtube.com/watch" then
					set tmp to name of t as string
					set str to text 1 thru -11 of tmp
				end if
			end tell
		end repeat
	end tell
end if
return str

Switch to window script :

tell application "Safari"
  repeat with w in windows
    repeat with t in tabs of w
      tell t
        if URL starts with "https://www.youtube.com/watch" then
          set current tab of w to t
          activate
          return true
        end if
      end tell
    end repeat
  end repeat
end tell
return false

I've made some improvements.
You'll find the new script I've made for Youtube :upside_down_face:
(Now it will display and go to the first Youtube window playing)

Currently playing script

set str to "" as string
	if ((str is equal to str) and (application "Safari" is running)) then
		tell application "Safari"
			repeat with t in tabs of windows
				tell t
					if URL starts with "https://www.youtube.com/watch" then
						set state to do JavaScript [¬
						"document", ¬
						".querySelectorAll('div[class*=\"-mode\"]')[0]", ¬
						".className", ¬
						".match(/(playing|paused|ended)-mode/)[1]"] ¬
						as text
					if state = "playing" then
						set tmp to name of t as string
						set str to text 1 thru -11 of tmp
					end if
				end if
				end tell
		end repeat
	end tell
end if
return str

Switch to window script

tell application "Safari"
	repeat with win in windows
		repeat with t in tabs of win
			tell t
				if URL starts with "https://www.youtube.com/watch" then
					set state to do JavaScript [¬
						"document", ¬
						".querySelectorAll('div[class*=\"-mode\"]')[0]", ¬
						".className", ¬
						".match(/(playing|paused|ended)-mode/)[1]"] ¬
						as text
					if state = "playing" then
						set current tab of win to t
						activate
						return true
					end if
				end if
			end tell
		end repeat
	end repeat
end tell
return false

any for Chrome? tried replacing Safari with Google Chrome but i think the applescript works differently (eg. no such thing as current tab).

Don't know, will be searching :slight_smile:

Just in case, if there are few windows, after activate of application you could add next command:
set index of win to 1

1 Like

At the beginning the currently playing script worked well, but now it show "can't get text 1 thru -11 of "Youtube" "