How Do I Get a Single YouTube Video Length From Keyboard Maestro in Chrome?

How Do I Get a Single YouTube Video Length From Keyboard Maestro in Chrome?

I am not good at programming, thank you very much.


Hey @guxianbang,

I don't think you can do this programmatically,

But you might be able to use Found Image condition to find the controls and then OCR the relevant data.


This is all greek to me, but... php - How to get video duration using YouTube API? - Stack Overflow

That stuff is old – 2015 and before...

The last method may or may not still be viable.

Using image detection or ocr is tricky as the video duration string only shown if you hover on the video area, so it is pretty manual process, in addition, the background of the duration string affects the recognition.

Here is the javascript solution for use in "Execute Javascript in Browser" action
If you just need the duration string ( eg 03:22 ) , use the following CSS

For those interested in using the YouTube api to get video duration, and then format it into duration str,
here's the code

let durationStr = (() => {
    const pDurationInSec = function getVideoDuration() {
        const currentVideoElement = document.querySelector('#movie_player video.html5-main-video');
        let durationInSec = 0;
        if (currentVideoElement) {
            if (!Number.isNaN(currentVideoElement.duration)) {
                durationInSec = Math.floor(currentVideoElement.duration);
        return durationInSec;

    const pDurationStr = function getFormattedTimeStr(inputDurationInSec) {
        let durationStr = ""; // Return empty string if duration is 0 sec.
        if (inputDurationInSec !== 0) {
            const hours = Math.floor(inputDurationInSec / (3600));
            const minutes = Math.floor((inputDurationInSec - (hours * 3600)) / 60);
            const seconds = inputDurationInSec % 60;

            durationStr = (hours ? `${hours}:` : "") +
                `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
        return durationStr;

    return pDurationStr;

1 Like