Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / common / extensions / docs / examples / api / tabs / screenshot / background.js
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // To make sure we can uniquely identify each screenshot tab, add an id as a
6 // query param to the url that displays the screenshot.
7 // Note: It's OK that this is a global variable (and not in localStorage),
8 // because the event page will stay open as long as any screenshot tabs are
9 // open.
10 var id = 100;
11
12 // Listen for a click on the camera icon. On that click, take a screenshot.
13 chrome.browserAction.onClicked.addListener(function() {
14
15   chrome.tabs.captureVisibleTab(function(screenshotUrl) {
16     var viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
17     var targetId = null;
18
19     chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
20       // We are waiting for the tab we opened to finish loading.
21       // Check that the tab's id matches the tab we opened,
22       // and that the tab is done loading.
23       if (tabId != targetId || changedProps.status != "complete")
24         return;
25
26       // Passing the above test means this is the event we were waiting for.
27       // There is nothing we need to do for future onUpdated events, so we
28       // use removeListner to stop getting called when onUpdated events fire.
29       chrome.tabs.onUpdated.removeListener(listener);
30
31       // Look through all views to find the window which will display
32       // the screenshot.  The url of the tab which will display the
33       // screenshot includes a query parameter with a unique id, which
34       // ensures that exactly one view will have the matching URL.
35       var views = chrome.extension.getViews();
36       for (var i = 0; i < views.length; i++) {
37         var view = views[i];
38         if (view.location.href == viewTabUrl) {
39           view.setScreenshotUrl(screenshotUrl);
40           break;
41         }
42       }
43     });
44
45     chrome.tabs.create({url: viewTabUrl}, function(tab) {
46       targetId = tab.id;
47     });
48   });
49 });