JavaScript で GoogleFeedAPI を使用して、RSS の記事を取得
JavaScript で GoogleFeedAPI を使用して、RSS を取得
JavaScript の Ajax 通信を行うと、サーバー側の同一ドメイン制約に引っかかり、 取得できません。GoogleFeedAPI を使用すると取得できるようになります。
GoogleFeedAPIについて
公式ドキュメントはこちら。 https://developers.google.com/feed/v1/devguide?hl=ja
関数 google.setOnLoadCallback( コールバック関数 )
に、コールバック関数をセットして使用する。
Result Objectは、指定しないとデフォルトで JSON で返ってくるようです。 サーバーサイドが XML でも JSON に変換して、取ってくるようです。 JSONで返ってくる要素は以下です。
- feed
- feedUrl
- The URL for the feed.
- author
- The feed author. Corresponds to the
element for the author in Atom.
- entries
- A list of all of the entries in the feed. Corresponds to the
element in Atom and the - element in RSS.
- mediaGroup
- A container for Media RSS feed results. All result properties nested under mediaGroups correspond exactly as documented in the Media RSS Specification. Media RSS is available only for feed entries newer than February 1st, 2010. Please refer to that specification for detailed information about Media RSS fields.
- content
- The body of this entry, inlcuding HTML tags. Since this value can contain HTML tags, you should display this value using elem.innerHTML = entry.content (as opposed to using document.createTextNode). Corresponds to the \content or \summary elements in Atom and the \description element in RSS.
- contentSnippet
- A snippet (< 120 characters) version of the content attribute. The snippet does not contain any HTML tags.
よく使うのは、 entries[]
オブジェクト配列になると思います。ここに各記事のタイトル、リンクなどが入ってます。
サンプルコード
getRssFeed(url, entries_num, id)
関数で url
にCodeZine さんのRSS のURL を使用し、 entries_num
に 5件指定し、 id
に"codezine"を入力し、<div id="codezine"></div>
に記事のリンク付きタイトルを表示するサンプルコードです。
結果
参考リンク
次は複数のRSS で非同期通信しながら取得できるか試していきます。