使用REST调用JSON自定义搜索API

时间:2016-04-21 18:41:51

标签: json google-chrome-extension xmlhttprequest google-custom-search asynccallback

我正在尝试使用javascript从Google Custom Search API获取JSON数据,但是在检索数据时却没有成功。

这适用于Chrome扩展程序。

我多次阅读Using REST文章,但仍然遇到问题。

我现在想做的就是成功获取结果,并在我的.html文件中显示JSON结果。感谢您的帮助/见解。

popup.js文件

function getCurrentTabUrl(callback) {
  var queryInfo = {
    active: true,
    currentWindow: true
  };

  chrome.tabs.query(queryInfo, function(tabs) {

    var tab = tabs[0];

    var url = tab.url;

    console.assert(typeof url == 'string', 'tab.url should be a string');

    callback(url);
  });

  // Most methods of the Chrome extension APIs are asynchronous. This means that
  // you CANNOT do something like this:
  //
  // var url;
  // chrome.tabs.query(queryInfo, function(tabs) {
  //   url = tabs[0].url;
  // });
  // alert(url); // Shows "undefined", because chrome.tabs.query is async.
}

function getSearchUrl(searchTerm, callback, errorCallback) {
  var mGoogleApiKey = "myAPIKEY";
  var mGoogleCustomSearchKey = "0000:myCustomSearchKey";
  var startIndex = "";
  var term= "+added+term";
  var searchUrl = 'https://www.googleapis.com/customsearch/v1?key=' + mGoogleApiKey + 
  '&num=10&cx=' + mGoogleCustomSearchKey + '&q=site:' + encodeURIComponent(searchTerm) + term;
  var x = new XMLHttpRequest();
  x.open('GET', searchUrl);
  // The Google Custom Search API responds with JSON, so let Chrome parse it.
  x.responseType = 'json';
  x.onload = function() {
    // Parse and process the response from Google Custom Search.
    var response = x.response;
    if (!response || !response.responseData || !response.responseData.results ||
        response.responseData.results.length === 0) {
      errorCallback('No response from Google Custom Search API!');
      return;
    }
    var firstResult = response.responseData.results[0];
    // Take the thumbnail instead of the full image to get an approximately
    // consistent image size.
    var imageUrl = firstResult.tbUrl;
    var width = parseInt(firstResult.tbWidth);
    var height = parseInt(firstResult.tbHeight);
    console.assert(
        typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
        'Unexpected respose from the Google Custom Search API!');
    callback(imageUrl, width, height);
  };
  x.onerror = function() {
    errorCallback('Network error.');
  };
  x.send();
}

function renderStatus(statusText) {
  document.getElementById('status').textContent = statusText;
}

document.addEventListener('DOMContentLoaded', function() {
  getCurrentTabUrl(function(url) {
    // Put the tab URL in Google search.
    renderStatus('Performing Google Custom Search for ' + url);

    getSearchUrl(url, function(imageUrl, width, height) {

      renderStatus('Search term: ' + url + '\n' +
          'Google custom search results: ' + imageUrl);
      var imageResult = document.getElementById('image-result');

      imageResult.width = width;
      imageResult.height = height;
      imageResult.src = imageUrl;
      imageResult.hidden = false;

    }, function(errorMessage) {
      renderStatus('Cannot display image. ' + errorMessage);
    });
  });
});

的manifest.json

{
  "manifest_version": 2,

  "name": "Getting started example",
  "description": "This extension shows a Google Custom search result for the current page",
  "version": "1.0",

  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ]
}

popup.html

<!doctype html>
<!--
 This page is shown when the extension button is clicked, because the
 "browser_action" field in manifest.json contains the "default_popup" key with
 value "popup.html".
 -->
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        font-family: "Segoe UI", "Lucida Grande", Tahoma, sans-serif;
        font-size: 100%;
      }
      #status {
        /* avoid an excessively wide status text */
        white-space: pre;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: 400px;
      }
    </style>

    <!--
      - JavaScript and HTML must be in separate files: see our Content Security
      - Policy documentation[1] for details and explanation.
      -
      - [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
     -->
    <script src="popup.js"></script>
  </head>
  <body>
    <div id="status"></div>
    <img id="image-result" hidden>
  </body>
</html>

0 个答案:

没有答案