Sharing count on Facebook, Twitter, and LinkedIn

时间:2024-01-14 17:49:02

  最近一段时间一直在研究有关Social Network的东西,这里有几个在当前国外主流社交网站上用来显示分享数量的API,记录一下,今后可能会用得着。

Sharing count on Facebook, Twitter, and LinkedIn

Facebook

  Facebook将FQL(Facebook Query Language)查询语句以URL参数的形式传递给服务器来实现查询,不仅可以查询当前页面的Sharing count,还可以查询许多数据。所涉及到的表和相关字段可以参考Facebook的官方文档:https://developers.facebook.com/docs/reference/fql/

  这里还有一个Facebook sharing counter的查询工具,直接输入要查询的页面的URL地址就可以查询该页面在Facebook中被分享过多少次了http://www.emetello.com/facebook-share-counter/

  下面是一段通过JavaScript代码在页面上显示分享到Facebook的次数,代码通过JQuery的Ajax方法调用Facebook的查询语句来获取分享次数的数字。注意观察Ajax中的url参数,其中query的值是一个FQL查询语句,当前查询link_stat表的share_count字段。Facebook的FQL查询语句不支持*通配符来查询表的所有字段。format参数用来指定返回值的类型,本例中为json对象字符串。timestamp参数是人为添加的,作用是为了避开可能的浏览器缓存。displaySharingCount方法负责在页面上显示获取到的结果,如果数字大于三位数,则只显示"500+",并给元素添加title属性用以显示完整的值;否则就直接显示值。

function displaySharingCount(val, objId) {
var blank = " ";
var id = "#" + objId
if (typeof (val) != "undefined") {
if (val.length > 3) {
$(id).attr("title", val);
$(id).text(blank + "500+");
}
else
$(id).text(blank + val);
}
} window.onload = function () {
var currUrl = encodeURIComponent(location.href); $.ajax({
url: "https://api.facebook.com/method/fql.query?query=select%20share_count%20from%20link_stat%20where%20url=%22" + currUrl + "%22&format=json&timestamp=" + new Date().getTime(),
type: "get",
datatype: "html",
async: true,
success: function (data) {
displaySharingCount(data[0].share_count, "Facebook_count");
}
});
};

Twitter & LinkedIn

  Twitter和LinkedIn在获取sharing count方面很相似,都是通过一个URL来获取返回结果,可以指定返回结果是json格式或jsonp。看下面的例子,通过jsonp来获取Twitter和LinkedIn的sharing count值。

function getTwitterCount(obj) {
displaySharingCount(obj.count, "Twitter_count");
} function getLinkedInCount(obj) {
displaySharingCount(obj.count, "LinkedIn_count");
} function createScript(id, src) {
var js, fjs = document.getElementsByTagName("script")[0];
js = document.getElementById(id);
if (js) {
document.removeChild(js);
}
js = document.createElement("script");
js.id = id;
js.src = src;
fjs.parentNode.insertBefore(js, fjs);
} window.onload = function () {
var currUrl = encodeURIComponent(location.href); createScript("Twitter_jscallback", "http://urls.api.twitter.com/1/urls/count.json?url=" + currUrl + "&format=jsonp&callback=getTwitterCount");
createScript("LinkedIn_jscallback", "http://www.linkedin.com/countserv/count/share?url=" + currUrl + "&format=jsonp&callback=getLinkedInCount");
};

  LinkedIn的官方网站上有关于如何使用sharing count的介绍:https://developer.linkedin.com/retrieving-share-counts-custom-buttons

  有一个地方需要注意,那就是当前页面的URL字符串是大小写敏感的,而且是否encoded也会有影响。例如下面这几个URL,虽然指向的都是同一个页面,但是获取到的sharing count也会有区别:

http://www.cnblogs.com/jaxu

http://www.cnblogs.com/Jaxu

http%3A%2F%2Fwww.cnblogs.com%2Fjaxu