在客户端创建链接预览,如 Facebook/LinkedIn [英] Create link previews on the client side, like in Facebook/LinkedIn
问题描述
我正在创建一个带有输入框的网络应用程序,用户可以在其中输入任何内容,包括 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 是否有用于制作链接预览"文本和图标的开源代码,例如在 facebook 中?.所以我们可以使用这个链接 http://api.embed.ly/1/oembed?url=YOUR-URL 通过 http GET 我们以 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屋!