如何从web url加载元数据,类似于facebook在状态更新时发布url的做法.

How to load metadata from web url similar to what facebook doing when we post url on status update...?

本文关键字:url 更新 状态 facebook web 加载 元数据 类似于      更新时间:2023-09-26

我想使用AngularJS/Javascript从网站url加载元数据,如标题、徽标和描述,类似于粘贴网站url时加载元数据的facebook状态更新功能。这方面有API吗?

我认为它不是API;而是一种智能算法,它在后台提取内容(HTTPGET),读取元数据并为您创建视图。

你也应该能够做到这一点。

对URL执行HTTP GET并读取元数据。

<meta property="og:image" content="[url to image]" />
<meta property="og:title" content="[page name]" />
<meta property="og:description" content="[content description]" />

实际上,使用HTML5代理是可能的:

读取所有属性的实用程序函数(仅针对此示例):

(function($) {
    $.fn.getAttributes = function() {
        var attributes = {}; 
        if( this.length ) {
            $.each( this[0].attributes, function( index, attr ) {
                attributes[ attr.name ] = attr.value;
            } ); 
        }
        return attributes;
    };
})(jQuery);

A代码:

$.get(
    'http://www.corsproxy.com/' +
    'en.wikipedia.org/wiki/Cross-origin_resource_sharing',
    function(response) {
        var a = $(response);
        for(var i = 0; i < a.length; i++) {
            if (typeof $(a[i]).prop("tagName") != 'undefined' && $(a[i]).prop("tagName").toLowerCase() == 'meta')
            console.log($(a[i]).getAttributes());
        }
});

工作原理:corproxy.com上的代理使用CORS(HTML5功能来解决同源策略的问题)。详细阅读这个答案用jQueryAJAX加载跨域端点。

然后从页面中创建jQuery对象,搜索所有的元标记并获取它们的属性(根据需要选择它们)。

如果你害怕使用第三方网站,那么唯一的方法就是在服务器上创建一个脚本,通过AJAX向其发送url,将页面加载到服务器并返回给客户端,然后找到所有的元标签。

如果你不想加载整个页面,你可以只加载第一部分(其中包含标签-根据HTML规范,所有标签都应该在里面):

var xhr = new XMLHttpRequest();
xhr.addEventListener("progress", updateProgress, false);
xhr.addEventListener("load", transferComplete, false);
xhr.addEventListener("error", transferFailed, false);
xhr.addEventListener("abort", transferCanceled, false);
xhr.open("GET", 'http://www.corsproxy.com/' +
    'en.wikipedia.org/wiki/List_of_law_clerks_of_the_Supreme_Court_of_the_United_States?1234', true);
xhr.send(null);
var nextLine = 0;
var resp = '';
// progress on transfers from the server to the client (downloads)
function updateProgress(evt) {
    resp = xhr.response.slice(nextLine);
    console.log(resp.length);
    if (resp.indexOf('</head>') != -1) {
        var a = $(resp);
        for(var i = 0; i < a.length; i++) {
            if (typeof $(a[i]).prop("tagName") != 'undefined' && $(a[i]).prop("tagName").toLowerCase() == 'meta')
                console.log($(a[i]).getAttributes());
        }
        xhr.abort();
    }
    nextLine = xhr.response.length;
}
function transferComplete(evt) {
    console.log("The transfer is complete.");
}
function transferFailed(evt) {
    console.log("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
    console.log("The transfer has been canceled by the user.");
}