Get YouTube or Vimeo Thumbnails in one shot with jQuery

后端 未结 5 449
陌清茗
陌清茗 2021-02-06 19:44

I\'m trying to put YouTube thumbnail and Vimeo thumbnail together in the same script, but its not really easy for me because I\'m a new to jQuery.

I would to ask if some

5条回答
  •  粉色の甜心
    2021-02-06 20:23

    You do this by observing that YouTube video thumbnails have a distinct URL pattern, which you can generate by parse out the video id. Vimeo thumbnails can be obtained similarly, but parsing out the video id and then using the simple API to obtain the link to the thumbnail.

    I wrote some code to do this for this Meta question; it's not particularly clean but it should work:

    function processURL(url, success){
        var id;
    
        if (url.indexOf('youtube.com') > -1) {
            id = url.split('/')[1].split('v=')[1].split('&')[0];
            return processYouTube(id);
        } else if (url.indexOf('youtu.be') > -1) {
            id = url.split('/')[1];
            return processYouTube(id);
        } else if (url.indexOf('vimeo.com') > -1) {
            if (url.match(/^vimeo.com\/[0-9]+/)) {
                id = url.split('/')[1];
            } else if (url.match(/^vimeo.com\/channels\/[\d\w]+#[0-9]+/)) {
                id = url.split('#')[1];
            } else if (url.match(/vimeo.com\/groups\/[\d\w]+\/videos\/[0-9]+/)) {
                id = url.split('/')[4];
            } else {
                throw new Error('Unsupported Vimeo URL');
            }
    
            $.ajax({
                url: 'http://vimeo.com/api/v2/video/' + id + '.json',
                dataType: 'jsonp',
                success: function(data) {
                    sucess(data[0].thumbnail_large);
                }
            });
        } else {
            throw new Error('Unrecognised URL');
        }
    
        function processYouTube(id) {
            if (!id) {
                throw new Error('Unsupported YouTube URL');
            }
    
            sucess('http://i2.ytimg.com/vi/' + id + '/hqdefault.jpg');
        }
    }
    

    The function uses a callback because Vimeo API calls are asynchronous.

提交回复
热议问题