在客户端创建链接预览,例如在Facebook / LinkedIn中

时间:2014-06-05 07:57:40

标签: javascript web-scraping

我正在创建一个带有输入框的Web应用程序,用户可以在其中编写任何内容,包括URL。我想创建像Facebook和LinkedIn这样的链接预览:

enter image description here

抓取给定的网址并显示其主图像和标题,而不进行服务器往返。有没有办法在浏览器中执行此操作?

3 个答案:

答案 0 :(得分:7)

经过几个小时的谷歌搜索,我自己找到了答案。 SO Is there open-source code for making 'link preview' text and icons, like in facebook?已经存在一个问题。所以我们可以通过http GET使用这个链接http://api.embed.ly/1/oembed?url=YOUR-URL,我们以json格式获取元标记。 我使用JSdom编写了我自己的代码,这里是代码......

服务器端代码:

app.post( '/scrapUrl/', function( req, res ) {

    var jsdom = require( 'jsdom' );
    var jsonRes = {};
    jsdom.env( {
        url: req.body.url,
        scripts: [ "http://code.jquery.com/jquery.js" ],
        done: function( error, window ) {
          var $ = window.$;

          $( 'meta' ).each( function() {
            var name = $( this ).attr( 'property' );
            var value = $( this ).attr( 'content' );
            if ( name ) {
              jsonRes[ name.slice( 3 ) ] = value;
              console.log( name + ": " + value );
            }
          } );
          res.send( jsonRes );
        }
    } );
} );

和角度代码

$http.post( '/scrapUrl/', {
    url: url  //send the url U need to scrape
} ).then( function( res ) {
    console.log(res.data)//U get the meta tags as json object
});

获得JSON对象后,您可以以任何您想要的样式显示它。

答案 1 :(得分:2)

如果有人仍在寻找答案,我建议您查看http://ogp.me。 它适用于Telegram messenger,Facebook,Discord等。

我在这个项目https://github.com/pBouillon/Sublime_text_snippets/blob/master/html_core.sublime-snippet

中做了一个使用它的框架

<head>
  <!-- open graph -->
    <!-- Informations -->
      <meta property="og:description" content="OPEN_GRAPH_DESCRIPTION" />
      <meta property="og:title" content="OPEN_GRAPH_TITLE" />
      <meta property="og:type"  content="website" />
      <meta property="og:url"   content="WEBSITE_URL" />
    <!-- Image -->
      <meta property="og:image" content="URL_TO_IMAGE" />
      <meta property="og:image:alt"    content="Website icon" />
      <meta property="og:image:height" content="80" />
      <meta property="og:image:secure_url" content="URL_TO_IMAGE" />
      <meta property="og:image:type"  content="image/png" />
      <meta property="og:image:width" content="80" />
      <meta property="og:locale" content="en_GB" />
</head>

答案 2 :(得分:0)

是的,您可以在客户端上完全生成链接预览,无论如何,这都是应该生成链接预览的方式,以提高效率并避免DOS对服务器的操作。

要找到链接预览的客户端库,请search GitHub for "link preview", and narrow down the search to JavaScript