Search code examples
swiftmacosbrowseryoutubeapplescript

Access web browser tabs and read website information from a native MacOS app


I'm trying to understand how to determine if a YouTube video/s is playing in a tab/s on a web browser (Chrome or Safari) and retrieve information like name of the video and the YouTube channel and play or pause the video. Similar to Bearded Spice. I've tried to understand the code of Bearded Spice, but I'm not familiar with Objective-C and there is no extensive documentation.

I know that tabs can be iterated thought and headings can be retrieved using AppleScript. But I'm unable to get the state of the player and some information about the video playing. I don't want to use Chrome and Safari extensions as I'm trying to achieve this using a native app for MacOS. Please point me in the right direction to achieve this.


Solution

  • This AppleScript code will Play or Paue any YouTube video which is loaded in any Google Chrome tab whether the browser is visible or not and whether the tab is visible or not. Tested on latest version of OS Sierra.

    -- Google Chrome Version
    
    to clickClassName(theClassName, elementnum)
        if application "Google Chrome" is running then
            try
                tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
                set youtubeTabs to item 1 of the result
                tell application "Google Chrome"
                    execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
                end tell
            end try
        end if
    end clickClassName
    
    
    clickClassName("ytp-play-button ytp-button", 0)
    

    This Returns the URLs for Chrome

    tell application "Google Chrome" to URL of tabs of window 1 whose title contains "youtube"
    

    This AppleScript code will Play or Paue any YouTube video which is loaded in the active tab of a Safari browser window

    -- Safari Version
    
    to clickClassName2(theClassName, elementnum)
        if application "Safari" is running then
            try
                tell application "Safari"
                    tell window 1 to set current tab to tab 1 whose URL contains "youtube"
                    do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
                end tell
            end try
        end if
    end clickClassName2
    
    clickClassName2("ytp-play-button ytp-button", 0)
    

    This will return the URLs of the YouTube windows with the videos

    tell application "Safari" to URL of tabs of window 1 whose name contains "youtube"
    

    Similar Post With Xcode Example