Check out this code snippet:
let url = URL;
let imageURL = '';
$.getJSON("https://graph.facebook.com/?id="+encodeURIComponent(url)+"&scrape=true&method=post",
function (data) {
let json_data = JSON.stringify(data);
json_data = json_data.replace(/\s+/g, ' ');
let obj = jQuery.parseJSON(json_data);
imageURL = obj.image[0].url;
alert(imageURL+'Facebook');
if(imageURL == ''){
$.getJSON("//query.yahooapis.com/v1/public/yql?q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"+encodeURIComponent(url)+"%27%20AND%20xpath=%27descendant-or-self::meta%27&format=json&callback=?"
, function(data) {
let res = $.grep(data.query.results.meta, function(image, key) {
return image.hasOwnProperty("property") && image.property === "og:image"
});
if (res.length > 0) {
let imageURL = res[0].content;
alert(imageURL+'Pinterest');
});
}
});
Sometimes the code works fine, but there are certain cases where it fails, such as with URLs from Phandroid like
http://phandroid.com/2015/09/25/galaxy-s7-february/
.
In these cases, the first method fails to get obj.image[0].url;
since the JSON object doesn't exist. Since imageURL
was initially blank, the if condition should execute but it doesn't. No alerts are triggered in this scenario. How should I proceed?