在客户端上创建链接预览,例如在Facebook/LinkedIn中 [英] Create link previews on the client side, like in Facebook/LinkedIn

查看:41
本文介绍了在客户端上创建链接预览,例如在Facebook/LinkedIn中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a web app with an input box where the user can write anything, including URLs. I want to create a link preview like Facebook and LinkedIn does:

抓取给定的URL并显示其主图像和标题,而无需服务器往返.有没有办法在浏览器中做到这一点?

Scrape the given URL and display its main image and heading, without a server round-trip. Is there a way to do this in the browser?

推荐答案

经过数小时的谷歌搜索,我自己找到了答案.SO .因此,我们可以使用此链接 http://api.embed.ly/1/oembed通过http GET的?url = YOUR-URL ,我们以json格式获取元标记.我使用 JSdom 编写了自己的代码,代码在这里...

After hours of googling I found the answer myself.. there is already a question in SO Is there open-source code for making 'link preview' text and icons, like in facebook? . So we can use this link http://api.embed.ly/1/oembed?url=YOUR-URL via http GET where we get the meta tags in json format.. I wrote my own code using JSdom and here goes the code...

服务器端代码:

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对象,就可以按照您想要的任何样式显示它.

Once you get the JSON object you can display it in whatever style you want.

这篇关于在客户端上创建链接预览,例如在Facebook/LinkedIn中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆