はしくれエンジニアもどきのメモ

情報系技術・哲学・デザインなどの勉強メモ・備忘録です。

JavaScript で GoogleFeedAPI を使用して、RSS の記事を取得

JavaScript で GoogleFeedAPI を使用して、RSS を取得

JavaScriptAjax 通信を行うと、サーバー側の同一ドメイン制約に引っかかり、 取得できません。GoogleFeedAPI を使用すると取得できるようになります。

Ajax 通信の同一ドメイン制約の話はまた今度に。

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.
    • title
      The feed title. Corresponds to theelement in Atom and theelement in RSS.
    • link
      The URL for the HTML version of the feed. Corresponds to the element in Atom and the element in RSS.
    • description
      The feed description. Corresponds to the \subtitle element in Atom and the \description element in RSS.
    • 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.
      • title
        The entry title. Corresponds to theelement in Atom and theelement in RSS.
      • link
        The URL for the HTML version of the entry. Corresponds to the element in Atom and the element in RSS.
      • 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.
      • publishedDate
        The string date on which the entry was published of the form "13 Apr 2007 12:40:07 -0700". You can parse the date with new Date(entry.publishedDate). Corresponds to the \published element in Atom and the \pubdate element in RSS.
      • categories
        A list of string tags for the entry. Corresponds to the term attribute for the \category element in Atom and the \category element in RSS.

よく使うのは、 entries[] オブジェクト配列になると思います。ここに各記事のタイトル、リンクなどが入ってます。

サンプルコード

getRssFeed(url, entries_num, id) 関数で urlCodeZine さんのRSS のURL を使用し、 entries_numに 5件指定し、 id に"codezine"を入力し、<div id="codezine"></div> に記事のリンク付きタイトルを表示するサンプルコードです。

gist5cf352b1c04e14671b96

結果

CodeZine RSSから記事のリンク付きタイトルを5件取得するサンプルの結果

次は複数のRSS で非同期通信しながら取得できるか試していきます。