Skip to content

Instantly share code, notes, and snippets.

@Aziz-Rahman
Last active January 18, 2017 22:46
Show Gist options
  • Save Aziz-Rahman/efb2fbe4c1c926a00d3f to your computer and use it in GitHub Desktop.
Save Aziz-Rahman/efb2fbe4c1c926a00d3f to your computer and use it in GitHub Desktop.
Get open grap from url with JSON
$('a#suggest_title').bind( "click", function(event) {
event.preventDefault();
// http://stackoverflow.com/questions/29997121/how-to-get-page-open-graph-metadata-via-jquery
var ogPostUrl = $('input#post_url').val();
$.getJSON("//query.yahooapis.com/v1/public/yql?"
+ "q=SELECT%20*%20FROM%20html%20WHERE%20url=%27"
+ encodeURIComponent(ogPostUrl)
+ "%27%20AND%20xpath=%27descendant-or-self::meta%27"
+ "&format=json&callback=?"
, function(data) {
// `data`:`json` returned from request
console.log(data);
// filter returned `results.meta` array for
// object having property `property`:`og:*` `meta` elements ;
// and has `property` `og:image`
var title = $.grep(data.query.results.meta, function(image, key) {
return image.hasOwnProperty("property") && image.property === "og:title"
});
if (title.length > 0) {
console.log(title[0].property);
$("#post-title").val(title[0].content);
};
var desc = $.grep(data.query.results.meta, function(image, key) {
return image.hasOwnProperty("property") && image.property === "og:description"
});
if (desc.length > 0) {
console.log(desc[0].property);
$("#post-desc").text(desc[0].content);
};
});
});
Copy link

ghost commented Jan 18, 2017

data.query should be check for null before data.query.results.meta sometime yahoo API return null answer on valid webpage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment