1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /* This is a JavaScript module (JSM) to be imported via
6   Components.utils.import() and acts as a singleton.
7   Only the following listed symbols will exposed on import, and only when
8   and where imported. */
9
10const EXPORTED_SYMBOLS = ["BrowserTabs"];
11
12const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
13
14Cu.import("resource://services-sync/main.js");
15
16var BrowserTabs = {
17  /**
18   * Add
19   *
20   * Opens a new tab in the current browser window for the
21   * given uri.  Throws on error.
22   *
23   * @param uri The uri to load in the new tab
24   * @return nothing
25   */
26  Add: function(uri, fn) {
27    // Open the uri in a new tab in the current browser window, and calls
28    // the callback fn from the tab's onload handler.
29    let wm = Cc["@mozilla.org/appshell/window-mediator;1"]
30               .getService(Ci.nsIWindowMediator);
31    let mainWindow = wm.getMostRecentWindow("navigator:browser");
32    let newtab = mainWindow.getBrowser().addTab(uri);
33    mainWindow.getBrowser().selectedTab = newtab;
34    let win = mainWindow.getBrowser().getBrowserForTab(newtab);
35    win.addEventListener("load", function() { fn.call(); }, true);
36  },
37
38  /**
39   * Find
40   *
41   * Finds the specified uri and title in Weave's list of remote tabs
42   * for the specified profile.
43   *
44   * @param uri The uri of the tab to find
45   * @param title The page title of the tab to find
46   * @param profile The profile to search for tabs
47   * @return true if the specified tab could be found, otherwise false
48   */
49  Find: function(uri, title, profile) {
50    // Find the uri in Weave's list of tabs for the given profile.
51    let engine = Weave.Service.engineManager.get("tabs");
52    for (let [guid, client] of Object.entries(engine.getAllClients())) {
53      if (!client.tabs) {
54        continue;
55      }
56      for (let key in client.tabs) {
57        let tab = client.tabs[key];
58        let weaveTabUrl = tab.urlHistory[0];
59        if (uri == weaveTabUrl && profile == client.clientName)
60          if (title == undefined || title == tab.title)
61            return true;
62      }
63    }
64    return false;
65  },
66};
67
68