// Credit: https://gist.github.com/yangshun/9892961 const video = { parse: function(url) { // - Supported YouTube URL formats: // - http://www.youtube.com/watch?v=My2FRPA3Gf8 // - http://youtu.be/My2FRPA3Gf8 // - https://youtube.googleapis.com/v/My2FRPA3Gf8 // - Supported Vimeo URL formats: // - http://vimeo.com/25451551 // - http://player.vimeo.com/video/25451551 // - Also supports relative URLs: // - //player.vimeo.com/video/25451551 url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/); if (RegExp.$3.indexOf('youtu') > -1) { var type = 'youtube'; } else if (RegExp.$3.indexOf('vimeo') > -1) { var type = 'vimeo'; } return { type: type, id: RegExp.$6 }; }, // Returns an iframe of the video with the specified URL. createEmbed: function(url, width, height) { var self = this; var videoObj = self.parse(url); var iframe = document.createElement('iframe'); iframe.width = width || 560; iframe.height = height || 315; iframe.frameborder = 0; iframe.setAttribute('allowFullScreen', ''); if (videoObj.type == 'youtube') { iframe.src = '//www.youtube.com/embed/' + videoObj.id; iframe.allow = "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"; } else if (videoObj.type == 'vimeo') { iframe.src = '//player.vimeo.com/video/' + videoObj.id; iframe.allow = "autoplay; fullscreen"; } return iframe; }, // Obtains the video's thumbnail and passed it back to a callback function. getThumbnail: function(url, cb) { var self = this; var videoObj = self.parse(url); var thumbUrl; switch (videoObj.type) { case 'youtube': thumbUrl = '//img.youtube.com/vi/' + videoObj.id + '/maxresdefault.jpg'; break; case 'vimeo': thumbUrl = '//i.vimeocdn.com/video/' + videoObj.id + '_640.jpg'; break; default: thumbUrl = ''; break; } return thumbUrl; }, }; // Example document.querySelector('.video').appendChild(video.createEmbed('https://www.youtube.com/watch?v=acHKPu4oIro'))