Can AppleScript detect if Netflix or YouTube is playing?

Solution 1:

Here is one way you can test if video is playing in Safari.

Example AppleScript code:

if (do shell script "pmset -g | grep -m 1 'displaysleep'") ¬
    contains "display sleep prevented by Safari" then
    
    --  # Video is playing.
    --  # Do something when video is playing.
    
else
    
    --  # Video is not playing.
    --  # Do something else when video is not playing.
    
end if

Notes:

Tested in macOS Catalina.

The contains "display sleep prevented by Safari" clause could actually only contain contains "Safari" and it would work. If you have, e.g. Firefox playing video you would use just firefox in that clause, and just Google Chrome for Google Chrome.

Generally speaking parentheses around the do shell script command are not necessary, except in this use case to allow for the use of the line continuation character, ¬, to have been placed where it is.