Home | History | Annotate | Download | only in contentscript_xhr
      1 <!DOCTYPE html>
      2 <!--
      3  * Copyright (c) 2010 The Chromium Authors. All rights reserved.  Use of this
      4  * source code is governed by a BSD-style license that can be found in the
      5  * LICENSE file.
      6 -->
      7 <html>
      8   <head>
      9   </head>
     10   <body>
     11     <script>
     12       /**
     13        * Performs an XMLHttpRequest to Twitter's API to get trending topics.
     14        * @param callback Function If the response from fetching url has a
     15        *     HTTP status of 200, this function is called with a JSON decoded
     16        *     response.  Otherwise, this function is called with null.
     17        */
     18       function fetchTwitterFeed(callback) {
     19         var xhr = new XMLHttpRequest();
     20         xhr.onreadystatechange = function(data) {
     21           if (xhr.readyState == 4) {
     22             if (xhr.status == 200) {
     23               var data = JSON.parse(xhr.responseText);
     24               callback(data);
     25             } else {
     26               callback(null);
     27             }
     28           }
     29         }
     30         // Note that any URL fetched here must be matched by a permission in
     31         // the manifest.json file!
     32         var url = 'http://search.twitter.com/trends/current.json?exclude=hashtags';
     33         xhr.open('GET', url, true);
     34         xhr.send();
     35       };
     36 
     37       /**
     38        * Handles data sent via chrome.extension.sendRequest().
     39        * @param request Object Data sent in the request.
     40        * @param sender Object Origin of the request.
     41        * @param callback Function The method to call when the request completes.
     42        */
     43       function onRequest(request, sender, callback) {
     44         // Only supports the 'fetchTwitterFeed' method, although this could be
     45         // generalized into a more robust RPC system.
     46         if (request.action == 'fetchTwitterFeed') {
     47           fetchTwitterFeed(callback);
     48         }
     49       };
     50 
     51       // Wire up the listener.
     52       chrome.extension.onRequest.addListener(onRequest);
     53     </script>
     54   </body>
     55 </html>