Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JSONP gets specific steps on the number of Posts on Twitter and Facebook


May 08, 2021 JSON


Table of contents


Twitter and Facebook require authentication to get the number of articles, but it turns out that you can get this information through JSONP, and this article describes how to use some simple code to get and skip the verification step, please refer to the steps below.

JavaScript code

I'll use basic JavaScript to show you how to do this:

The code is as follows:
// 获取文章数量的封装对象 
var socialGetter = (function() { 
/* JSONP: 获取脚本的工具函数 */ 
function injectScript(url) { 
var script = document.createElement('script'); 
script.async = true; 
script.src = url; 
document.body.appendChild(script); 
} 

return { 
getFacebookCount: function(url, callbackName) { 
injectScript('https://graph.facebook.com/?id=' + url + '&callback=' + callbackName); 
}, 
getTwitterCount: function(url, callbackName) { 
injectScript('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=' + callbackName); 
} 
}; 
})(); 

// 回调方法 
function twitterCallback(result) { 
result.count && console.log('The count is: ', result.count); 
} 
function facebookCallback(result) { 
result.shares && console.log('The count is: ', result.shares); 
} 

// 调用 
socialGetter.getFacebookCount('http://davidwalsh.name/twitter-facebook-jsonp', 'facebookCallback'); 
socialGetter.getTwitterCount('http://davidwalsh.name/twitter-facebook-jsonp', 'twitterCallback'); 
Because there are so many lightweight micro-frameworks dealing with JSONP, perhaps the most important part of this article is getting the url of the information. C hoose your JSONP tool as needed and customary!

Twitter and Facebook are certainly limited in the number and frequency of these requests, so if your site is visiting a lot, JSONP is likely to be blocked or blocked. A quick solution is to store the number of articles in sessionStorage, but only for a single user. If you're running a website with a high traffic flow, you'd better choose to crawl the data on the server side and cache it and automatically refresh it over a period of time.

Foreign social networking sites get the number of shares APIs

Twitter

GET URL:

http://cdn.api.twitter.com/1/urls/count.JSon?url=http://stylehatch.co

Return results:

{
    "count":528,
    "url":"http://stylehatch.co/"
}

Facebook

GET URL:

http://graph.facebook.com/?id=http://stylehatch.co

Return results:

{
   "id": "http://stylehatch.co",
   "shares": 61
}

Pinterest


GET URL:

http://api.pinterest.com/v1/urls/count.json?callback=&url=http://stylehatch.co

Return results:

({"count": 0, "url": "http://stylehatch.co"})

Linkedin

GET URL:

http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&format=json

Return results:

{
    "count":17,
    "fCnt":"17",
    "fCntPlusOne":"18",
    "url":"http:\/\/stylehatch.co"
}

Google Plus

POST URL:

https://clients6.google.com/rpc?key=YOUR_API_KEY

POST body:

[{
    "method":"pos.plusones.get",
    "id":"p",
    "params":{
        "nolog":true,
        "id":"http://stylehatch.co/",
        "source":"widget",
        "userId":"@viewer",
        "groupId":"@self"
        },
    "jsonrpc":"2.0",
    "key":"p",
    "apiVersion":"v1"
}]

Return results:

[{
    "result": { 
        "kind": "pos#plusones", 
        "id": "http://stylehatch.co/", 
        "isSetByViewer": false, 
        "metadata": {
            "type": "URL", 
            "globalCounts": {
                "count": 3097.0
            }
        }
    } ,
    "id": "p"
}]

StumbledUpon

GET URL:

http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://stylehatch.co

Return results:

{
    "result":{
        "url":"http:\/\/stylehatch.co\/",
        "in_index":true,
        "publicid":"1iOLcK",
        "views":39,
        "title":"Style Hatch - Hand Crafted Digital Goods",
        "thumbnail":"http:\/\/cdn.stumble-upon.com\/mthumb\/941\/72725941.jpg",
        "thumbnail_b":"http:\/\/cdn.stumble-upon.com\/bthumb\/941\/72725941.jpg",
        "submit_link":"http:\/\/www.stumbleupon.com\/submit\/?url=http:\/\/stylehatch.co\/",
        "badge_link":"http:\/\/www.stumbleupon.com\/badge\/?url=http:\/\/stylehatch.co\/",
        "info_link":"http:\/\/www.stumbleupon.com\/url\/stylehatch.co\/"
    },
    "timestamp":1336520555,
    "success":true
}

Here is a website encapsulated with a small plug-in, specifically used to display the social networking site sharing toolbar on the page, can be taken directly to use, more convenient! http://sharrre.com/

Facebook, Twitter, linkedIn are commonly used to give examples of calling APIs:

// Facebook
$.getJSON("http://graph.facebook.com/?id=http://stylehatch.co", function (d) {
    $("#fackbook_count").text("The Facebook Share count is: " + d.shares);
});

// Twitter
$.getJSON("http://cdn.api.twitter.com/1/urls/count.json?url=http://stylehatch.co&callback=?", function (d) {
    $("#twitter_count").text("The Twitter Share count is: " + d.count);
});

// LinkedIn
$.getJSON("http://www.linkedin.com/countserv/count/share?url=http://stylehatch.co&callback=?", function (d) {
    $("#linkedin_count").text("The LinkdeIn Share count is: " + d.count);
});

The IE browser may not be able to get the data returned by Facebook correctly, so you can try adding a URL to the URL so that JQuery calls it as ASONP.

Facebook also has another API that returns XML data, called this:

$.get("http://api.facebook.com/method/links.getStats?urls=http://stylehatch.co", function (d) {
    $("#fackbook_count").text("The Facebook Share count is: " + $(d).find("total_count").text());
});

If a No Transport error occurs under Internet Explorer and you can't get the data returned by Facebook, try adding $.support.cors to the front of the JavaScript code. Allow cross-domain access to data.

Encapsulate the code

We encapsulate the APIs of the three social networking sites above, Facebook, Twitter, and LinkedIn, to facilitate page calls.

$.fn.getShareCount = function (url) {
    var self = this;
    var displayShareCount = function (val, obj) {
        if (!isNaN(val) && val > 0) {
            obj.show();
            if (val > 999) {
                obj.attr("title", val);
                obj.text("500+");
            }
            else
                obj.text(val);
        }
    };

    return {
        facebook: function () {
            $.get("http://api.facebook.com/method/links.getStats?urls=" + url, function (d) {
                var c = $(d).find("total_count").text();
                self.each(function () { displayShareCount(c, $(this)); });
            });
        },
        twitter: function () {
            $.getJSON("http://cdn.api.twitter.com/1/urls/count.json?url=" + url + "&callback=?", function (d) {
                self.each(function () { displayShareCount(d.count, $(this)); });
            });
        },
        linkedin: function () {
            $.getJSON("http://www.linkedin.com/countserv/count/share?url=" + url + "&callback=?", function (d) {
                self.each(function () { displayShareCount(d.count, $(this)); });
            });
        }
    };
};

Then call it on the page like this:

$(function () {
    var shareUrl = window.location.href.toLowerCase();

    $('#fackbook_count').getShareCount(shareUrl).facebook();
    $('#twitter_count').getShareCount(shareUrl).twitter();
    $('#linkedin_count').getShareCount(shareUrl).linkedin();
});