Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(36)

Side by Side Diff: chrome/common/extensions/docs/examples/tutorials/getstarted/popup.js

Issue 732943002: New Getting started example for extensions (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 6 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 /** 5 /**
6 * Global variable containing the query we'd like to pass to Flickr. In this 6 * Get the current URL.
7 * case, kittens!
8 * 7 *
9 * @type {string} 8 * @param {function(string)} callback - called when the URL of the current tab
9 * is found.
10 **/
11 function getCurrentTabUrl(callback) {
12 // Query filter to be passed to chrome.tabs.query - see
13 // https://developer.chrome.com/extensions/tabs#method-query
14 var queryInfo = {
15 active: true,
16 currentWindow: true
17 };
18
19 chrome.tabs.query(queryInfo, function(tabs) {
20 // chrome.tabs.query invokes the callback with a list of tabs that match the
21 // query. When the popup is opened, there is certainly a window and at least
22 // one tab, so we can safely assume that |tabs| is a non-empty array.
23 // A window can only have one active tab at a time, so the array consists of
24 // exactly one tab.
25 var tab = tabs[0];
26
27 // A tab is a plain object that provides information about the tab.
28 // See https://developer.chrome.com/extensions/tabs#type-Tab
29 var url = tab.url;
30
31 // tab.url is not set when you forget to declare the "tabs" permission in
32 // manifest.json.
not at google - send to devlin 2014/11/17 22:02:57 You should be able to rely on activeTab to get the
robwu 2014/11/17 22:26:11 Done.
33 console.assert(typeof url == 'string', 'tab.url should be a string');
34
35 callback(url);
36 });
37
38 // Most methods of the Chrome extension APIs are asynchronous. This means that
39 // you CANNOT do something like this:
40 //
41 // var url;
42 // chrome.tabs.query(queryInfo, function(tabs) {
43 // url = tabs[0].url;
44 // });
45 // alert(url); // Shows "undefined", because chrome.tabs.query is async.
46 }
47
48 /**
49 * @param {string} searchTerm - Search term for Google Image search.
50 * @param {function(string)} callback - Called when an image has been found.
51 * The callback gets the URL of the image.
52 * @param {function(string)} errorCallback - Called when the image is not found.
53 * The callback gets a string that describes the failure reason.
10 */ 54 */
11 var QUERY = 'kittens'; 55 function getImageUrl(searchTerm, callback, errorCallback) {
56 // Google image search - 100 searches per day.
57 var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
58 '?v=1.0&q=' + encodeURIComponent(searchTerm);
59 var x = new XMLHttpRequest();
60 x.open('GET', searchUrl);
61 // The Google image search API responds with JSON, so let Chrome parse it.
62 x.responseType = 'json';
63 x.onload = function() {
64 // Parse and process the response from Google Image Search.
not at google - send to devlin 2014/11/17 22:02:57 Does it reply with any sizing info? It'd be nice t
robwu 2014/11/17 22:26:11 Yes, the size is available. I have not used it tho
not at google - send to devlin 2014/11/17 23:14:03 The practical effect would be to avoid unnecessary
robwu 2014/11/17 23:18:54 What did you mean by that? Whether I can observe t
not at google - send to devlin 2014/11/17 23:24:05 An advantage of setting it up-front is that there'
robwu 2014/11/17 23:26:47 Okay, sounds plausible. I will submit a change tom
65 var response = x.response;
66 if (!response || !response.responseData || !response.responseData.results ||
67 response.responseData.results.length === 0) {
68 errorCallback('No response from Google Image search!');
69 return;
70 }
71 var firstResult = response.responseData.results[0];
72 var imageUrl = firstResult.url;
73 callback(imageUrl);
74 };
75 x.onerror = function() {
76 errorCallback('Network error.');
77 };
78 x.send();
79 }
12 80
13 var kittenGenerator = { 81 function renderStatus(statusText) {
14 /** 82 document.getElementById('status').textContent = statusText;
15 * Flickr URL that will give us lots and lots of whatever we're looking for. 83 }
16 *
17 * See http://www.flickr.com/services/api/flickr.photos.search.html for
18 * details about the construction of this URL.
19 *
20 * @type {string}
21 * @private
22 */
23 searchOnFlickr_: 'https://secure.flickr.com/services/rest/?' +
24 'method=flickr.photos.search&' +
25 'api_key=90485e931f687a9b9c2a66bf58a3861a&' +
26 'text=' + encodeURIComponent(QUERY) + '&' +
27 'safe_search=1&' +
28 'content_type=1&' +
29 'sort=interestingness-desc&' +
30 'per_page=20',
31 84
32 /** 85 function main() {
33 * Sends an XHR GET request to grab photos of lots and lots of kittens. The 86 getCurrentTabUrl(function(url) {
34 * XHR's 'onload' event is hooks up to the 'showPhotos_' method. 87 // Put the image URL in Google search.
35 * 88 renderStatus('Performing Google Image search for ' + url);
36 * @public
37 */
38 requestKittens: function() {
39 var req = new XMLHttpRequest();
40 req.open("GET", this.searchOnFlickr_, true);
41 req.onload = this.showPhotos_.bind(this);
42 req.send(null);
43 },
44 89
45 /** 90 getImageUrl(url, function(imageUrl) {
46 * Handle the 'onload' event of our kitten XHR request, generated in
47 * 'requestKittens', by generating 'img' elements, and stuffing them into
48 * the document for display.
49 *
50 * @param {ProgressEvent} e The XHR ProgressEvent.
51 * @private
52 */
53 showPhotos_: function (e) {
54 var kittens = e.target.responseXML.querySelectorAll('photo');
55 for (var i = 0; i < kittens.length; i++) {
56 var img = document.createElement('img');
57 img.src = this.constructKittenURL_(kittens[i]);
58 img.setAttribute('alt', kittens[i].getAttribute('title'));
59 document.body.appendChild(img);
60 }
61 },
62 91
63 /** 92 renderStatus('Search term: ' + url + '\n' +
64 * Given a photo, construct a URL using the method outlined at 93 'Google image search result: ' + imageUrl);
65 * http://www.flickr.com/services/api/misc.urlKittenl 94 document.getElementById('image-result').src = imageUrl;
66 *
67 * @param {DOMElement} A kitten.
68 * @return {string} The kitten's URL.
69 * @private
70 */
71 constructKittenURL_: function (photo) {
72 return "http://farm" + photo.getAttribute("farm") +
73 ".static.flickr.com/" + photo.getAttribute("server") +
74 "/" + photo.getAttribute("id") +
75 "_" + photo.getAttribute("secret") +
76 "_s.jpg";
77 }
78 };
79 95
80 // Run our kitten generation script as soon as the document's DOM is ready. 96 }, function(errorMessage) {
81 document.addEventListener('DOMContentLoaded', function () { 97 renderStatus('Cannot display image. ' + errorMessage);
82 kittenGenerator.requestKittens(); 98 });
99 });
100 }
101
102 document.addEventListener('DOMContentLoaded', function() {
103 main();
83 }); 104 });
not at google - send to devlin 2014/11/17 22:02:57 You could do just document.addEventListener('DOMC
robwu 2014/11/17 22:26:11 Done.
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698