获取 YouTube 封面

按照您的描述,如果最大尺寸的封面不一定存在,那这个只试图获取最大尺寸封面的小书签就不严谨。

然后小书签中对参数的替换,如果网址中存在其他参数也会产生错误。

我就把这两个细节给完善了一下,但简单测试下来发现,直接获取 maxresdefault 图片就会返回能够返回的最大尺寸封面,所以我自以为的严谨很可能是毫无必要的。(测试不充分,约等于猜测。

代码如下,欢迎探讨。

javascript:(function(){
  const suffix = ['maxresdefault', 'sddefault', 'hqdefault'];
  const getCover = (index=0)=>{
    const img = new Image();
    const coverUrl = window.location.search.replace(/(?:\?|&)v=(\w+)/,'https://i1.ytimg.com/vi/$1/')+suffix[index]+'.jpg';
    img.onload = ()=> window.location.href = coverUrl;
    img.onerror = ()=> getCover(++index);
    img.src = coverUrl;
  };
  getCover();
})()