javascriptjqueryjwplayerjwplayer6jwplayer7

Get User watched total time of a video in jwplayer


I want to capture Total Played/watched time of a video from jwplayer. using below sample code.

jwplayer("player").setup({
    "playlist": [
        {
            "sources": [
                {
                    "default": false,
                    "file": 'https://content.jwplatform.com/manifests/yp34SRmf.m3u8',
                    "label": "0",
                    "type": "hls",
                    "preload": "meta"
                }
            ]
        }
    ],
    "height": "240",
    "width": "100%",
    "aspectratio": "16:9",
    "stretching": "uniform",
    "controls": true,
    "autostart": true
});

jwplayer("player").on('time', function (e) {
    var count = this.getPosition();        
});

Could you please help me doing this.


Solution

  • The best way would be to rely on the JW Player events for this, specifically the on('time') event.

    let totalTimeWatched = 0;
    let previousPosition = 0;
    jwplayer().on('time', (e) => {
        const { position } = e;
        totalTimeWatched += (position - previousPosition);
        previousPosition = position;
    });
    

    If you do want to count time for ads, as well, you can use the adTime event, which has also has a position property.

    EDIT

    To account for seeking behavior you can use an additional listener, on('seek') to reset the previousPosition. See below:

    let totalTimeWatched = 0;
    let previousPosition = 0;
    jwplayer().on('time', (e) => {
        const { position } = e;
        totalTimeWatched += (position - previousPosition);
        previousPosition = position;
    });
    
    jwplayer().on('seek', (e) => {
        previousPosition = e.offset;
    });