Get YouTube or Vimeo Thumbnails in one shot with jQuery

后端 未结 5 447
陌清茗
陌清茗 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:21

    Also, Vimeo uses https://vimeo.com/n format so make the s optional and the id is the 4th[3] not 2nd[1] in the split array:

    function get_video_thumb(url, callback){
        var id = get_video_id(url);
    
        if (id['type'] == 'y') {
            return processYouTube(id);
        } else if (id['type'] == 'v') {
    
            $.ajax({
                url: 'http://vimeo.com/api/v2/video/' + id['id'] + '.json',
                dataType: 'jsonp',
                success: function(data) {
                    callback({type:'v', id:id['id'], url:data[0].thumbnail_large});
                }
            });
        }
    
        function processYouTube(id) {
            if (!id) {
                throw new Error('Unsupported YouTube URL');
            }
    
            callback({type:'y',id:id['id'],url:'http://i2.ytimg.com/vi/'+id['id'] + '/hqdefault.jpg'}); 
        }
    }
    
    function get_video_id(url) {
            var id;
            var a;
        if (url.indexOf('youtube.com') > -1) {
            id = url.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(/https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/)) {
            id = url.split('/')[3];
        } 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');
        }
    
        } else {
            throw new Error('Unrecognised URL');
        }
            a = {type:'v',id:id};
            return a;
        function processYouTube(id) {
            if (!id) {
                throw new Error('Unsupported YouTube URL');
            }
                    a = {type:'y',id:id};
            return(a); // default.jpg OR hqdefault.jpg
        }
    }
    

提交回复
热议问题