JSONP takes specific steps to get the number of posts on Twitter and Facebook

  • 2020-03-30 02:06:22
  • OfStack

Twitter and Facebook are used in the text, because the domestic is strong, so I think it is useful to get a JSONP inside the tool class.

My problem is that many popular APIs already require authentication to retrieve information.

Since I can access these pages and get information, why don't I use some simple code to get it and skip the validation step?
I think Twitter and Facebook require authentication to get the number of articles, but it turns out you can get that information through JSONP. Please refer to the following steps.

The JavaScript

I'll use basic JavaScript to show you how to do this:
 
//Gets a wrapper object for the number of articles
var socialGetter = (function() { 
 
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); 
} 
}; 
})(); 

//The 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://davidwalsh.name/twitter-facebook-jsonp', 'facebookCallback'); 
socialGetter.getTwitterCount('http://davidwalsh.name/twitter-facebook-jsonp', 'twitterCallback'); 

Because there are so many lightweight micro-frameworks that handle JSONP, the most important part of this article is probably the url to get the information. Choose your JSONP tool based on your needs and habits!

Twitter and Facebook certainly have limits on the number and frequency of these requests, so JSONP is likely to be blocked or blocked if your site gets a lot of traffic. If you're running a website with a lot of traffic, you might want to grab the data on the server side, cache it, and refresh it automatically for a certain amount of time.

Related articles: