This article mainly introduces how to use JSONP to get the number of Twitter and Facebook articles. For more information, see Twitter and Facebook in the original article, so what I think is useful is the tool class that gets JSONP.
Many popular APIs require authentication to obtain information.
Since I can access these pages and obtain information, why don't I use some simple code to retrieve and skip the verification step?
I think Twitter and Facebook require authentication to get the number of articles, but it turns out that you can get this information through JSONP. Refer to the following steps.
The JavaScript
I will use basic JavaScript to show you how to do this:
The Code is as follows:
// Obtain the number of encapsulated objects of the document
Var socialGetter = (function (){
/* JSONP: Get the tool function of the script */
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 );
}
};
})();
// Callback Method
Function twitterCallback (result ){
Result. count & console. log ('The count is: ', result. count );
}
Function facebookCallback (result ){
Result. shares & console. log ('The count is: ', result. shares );
}
// Call
SocialGetter. getFacebookCount ('HTTP: // davidworkshops. name/twitter-facebook-jsonp', 'facebookcallback ');
SocialGetter. getTwitterCount ('HTTP: // Davy. name/twitter-facebook-jsonp', 'twittercallback ');
Because there are many lightweight micro-frameworks to process JSONP, the most important part of this article may be the url for obtaining information. Select your JSONP tool based on your needs and habits!
Twitter and Facebook certainly have limits on the number and frequency of these requests. Therefore, if your website has a large access volume, JSONP may be blocked or blocked. A quick solution is to store the number of articles in sessionStorage, but this is only for a single user. If your website is running with a large amount of traffic, you 'd better capture and cache the data on the server side and refresh it automatically within a certain period of time.