关于javascript:使用html和jquery将网址粘贴到textarea中后,如何显示youtube视频数据详细信息,就像whatsapp一样?

How to display youtube video data details after pasting url in textarea using html and jquery, exactly like whatsapp does?

enter


您可以使用oEmbed界面检索视频的元数据。查看此答案以获取有关此信息的更多信息。

现在这里是该界面的问题,YouTube没有提供Access-Control-Allow-Origin标头,这使得其他网络服务很难向其发出请求。您的浏览器将阻止您尝试向YouTube发出的所有http请求

我们可以通过两种方式处理此问题:

第一个方法是在oembed接口周围创建一种package器。您使用后端服务创建一些端点,该端点向Youtube发出实际的http请求,然后您的应用程序向该端点发出ajax请求。看看我在上面链接的答案,以了解如何进行设置

第二种方法是肮脏的方法。我们将使用名为CorsAnywhere的代理服务来处理我们之前讨论的问题。

所以首先这是标记,我们将需要布置所有内容

1
2
3
4
      <img id="video-thumbnail">
    <h4 id="video-title"></h4>
 
  <textarea id="link" rows="8"></textarea>

标记的一些样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
html, body {
  padding: 0;
  margin: 0;
  width: 100%
}

#video-thumbnail {
  height: 100%;
  width: auto;
}

#video-link {
  display: inline-block;
  vertical-align: top;
}
.video-meta {
  display: block;
  height: 0;
  transition: height 150ms ease;
}

.video-meta.open {
  height: 150px;
}

.application {
  width: 500px;
  margin: auto;
}

.video-meta {
  width: 100%;
}

textarea {
  width: 100%;
}

最后是将推动整个事情发展的JS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    // Prefilter to auto-magically prepend cors anywhere domain to
jQuery.ajaxPrefilter(function(options) {
    if (options.crossDomain && jQuery.support.cors) {
        options.url = 'https://cors-anywhere.herokuapp.com/' + options.url;
      // Host local instance maybe?
    }
});

// Function that will retrieve the data for a particular video
function getVideoData(url) {
      var base = 'https://www.youtube.com/oembed?url={link}&format=json';

     var link = base.replace('{link}', url);
     var result = null;

      $.ajax({
          url: link,
          type: 'get',
          dataType: 'json',
          async: false, // Probably not the best thing. Just for demo purposes.
          success: function(data) {
              result = data;
          }
       });

     return result;
}

// Event handler for keyup event
$('#link').on('keyup', function() {
   $('.video-meta').removeClass('open');
   var link = $(this).val();

  // Check URL's maybe

   var data = getVideoData(link);

  // Check if we go valid response
    if(!data) {
      alert("Something went wrong");
      return;
    }

    // Set values
    $('#video-thumbnail').attr('src', data.thumbnail_url);
    $('#video-link').attr('href', link);
    $('#video-title').text(data.title);

    $('.video-meta').addClass('open');
});

这是一个正在工作的小提琴。希望对您有所帮助!