browser.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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 file,
  3. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const {utils: Cu} = Components;
  6. Cu.import("chrome://marionette/content/element.js");
  7. Cu.import("chrome://marionette/content/error.js");
  8. Cu.import("chrome://marionette/content/frame.js");
  9. this.EXPORTED_SYMBOLS = ["browser"];
  10. this.browser = {};
  11. const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
  12. /**
  13. * Get the <xul:browser> for the specified tab.
  14. *
  15. * @param {<xul:tab>} tab
  16. * The tab whose browser needs to be returned.
  17. *
  18. * @return {<xul:browser>}
  19. * The linked browser for the tab or null if no browser can be found.
  20. */
  21. browser.getBrowserForTab = function (tab) {
  22. if ("browser" in tab) {
  23. // Fennec
  24. return tab.browser;
  25. } else if ("linkedBrowser" in tab) {
  26. // Firefox
  27. return tab.linkedBrowser;
  28. } else {
  29. return null;
  30. }
  31. };
  32. /**
  33. * Return the tab browser for the specified chrome window.
  34. *
  35. * @param {nsIDOMWindow} win
  36. * The window whose tabbrowser needs to be accessed.
  37. *
  38. * @return {<xul:tabbrowser>}
  39. * Tab browser or null if it's not a browser window.
  40. */
  41. browser.getTabBrowser = function (win) {
  42. if ("BrowserApp" in win) {
  43. // Fennec
  44. return win.BrowserApp;
  45. } else if ("gBrowser" in win) {
  46. // Firefox
  47. return win.gBrowser;
  48. } else {
  49. return null;
  50. }
  51. };
  52. /**
  53. * Creates a browsing context wrapper.
  54. *
  55. * Browsing contexts handle interactions with the browser, according to
  56. * the current environment (desktop, B2G, Fennec, &c).
  57. *
  58. * @param {nsIDOMWindow} win
  59. * The window whose browser needs to be accessed.
  60. * @param {GeckoDriver} driver
  61. * Reference to the driver the browser is attached to.
  62. */
  63. browser.Context = class {
  64. /**
  65. * @param {<xul:browser>} win
  66. * Frame that is expected to contain the view of the web document.
  67. * @param {GeckoDriver} driver
  68. * Reference to driver instance.
  69. */
  70. constructor(win, driver) {
  71. this.window = win;
  72. this.driver = driver;
  73. // In Firefox this is <xul:tabbrowser> (not <xul:browser>!)
  74. // and BrowserApp in Fennec
  75. this.tabBrowser = browser.getTabBrowser(win);
  76. this.knownFrames = [];
  77. // Used in B2G to identify the homescreen content page
  78. this.mainContentId = null;
  79. // Used to set curFrameId upon new session
  80. this.newSession = true;
  81. this.seenEls = new element.Store();
  82. // A reference to the tab corresponding to the current window handle, if any.
  83. // Specifically, this.tab refers to the last tab that Marionette switched
  84. // to in this browser window. Note that this may not equal the currently
  85. // selected tab. For example, if Marionette switches to tab A, and then
  86. // clicks on a button that opens a new tab B in the same browser window,
  87. // this.tab will still point to tab A, despite tab B being the currently
  88. // selected tab.
  89. this.tab = null;
  90. this.pendingCommands = [];
  91. // We should have one frame.Manager per browser.Context so that we
  92. // can handle modals in each <xul:browser>.
  93. this.frameManager = new frame.Manager(driver);
  94. this.frameRegsPending = 0;
  95. // register all message listeners
  96. this.frameManager.addMessageManagerListeners(driver.mm);
  97. this.getIdForBrowser = driver.getIdForBrowser.bind(driver);
  98. this.updateIdForBrowser = driver.updateIdForBrowser.bind(driver);
  99. this._curFrameId = null;
  100. this._browserWasRemote = null;
  101. this._hasRemotenessChange = false;
  102. }
  103. /**
  104. * The current frame ID is managed per browser element on desktop in
  105. * case the ID needs to be refreshed. The currently selected window is
  106. * identified by a tab.
  107. */
  108. get curFrameId() {
  109. let rv = null;
  110. if (this.driver.appName == "B2G") {
  111. rv = this._curFrameId;
  112. } else if (this.tab) {
  113. rv = this.getIdForBrowser(browser.getBrowserForTab(this.tab));
  114. }
  115. return rv;
  116. }
  117. set curFrameId(id) {
  118. if (this.driver.appName != "Firefox") {
  119. this._curFrameId = id;
  120. }
  121. }
  122. /**
  123. * Retrieves the current tabmodal UI object. According to the browser
  124. * associated with the currently selected tab.
  125. */
  126. getTabModalUI() {
  127. let br = browser.getBrowserForTab(this.tab);
  128. if (!br.hasAttribute("tabmodalPromptShowing")) {
  129. return null;
  130. }
  131. // The modal is a direct sibling of the browser element.
  132. // See tabbrowser.xml's getTabModalPromptBox.
  133. let modals = br.parentNode.getElementsByTagNameNS(
  134. XUL_NS, "tabmodalprompt");
  135. return modals[0].ui;
  136. }
  137. /**
  138. * Close the current window.
  139. *
  140. * @return {Promise}
  141. * A promise which is resolved when the current window has been closed.
  142. */
  143. closeWindow() {
  144. return new Promise(resolve => {
  145. this.window.addEventListener("unload", ev => {
  146. resolve();
  147. }, {once: true});
  148. this.window.close();
  149. });
  150. }
  151. /** Called when we start a session with this browser. */
  152. startSession(newSession, win, callback) {
  153. callback(win, newSession);
  154. }
  155. /**
  156. * Close the current tab.
  157. *
  158. * @return {Promise}
  159. * A promise which is resolved when the current tab has been closed.
  160. *
  161. * @throws UnsupportedOperationError
  162. * If tab handling for the current application isn't supported.
  163. */
  164. closeTab() {
  165. // If the current window is not a browser then close it directly. Do the
  166. // same if only one remaining tab is open, or no tab selected at all.
  167. if (!this.tabBrowser || this.tabBrowser.tabs.length === 1 || !this.tab) {
  168. return this.closeWindow();
  169. }
  170. return new Promise((resolve, reject) => {
  171. if (this.tabBrowser.closeTab) {
  172. // Fennec
  173. this.tabBrowser.deck.addEventListener("TabClose", ev => {
  174. resolve();
  175. }, {once: true});
  176. this.tabBrowser.closeTab(this.tab);
  177. } else if (this.tabBrowser.removeTab) {
  178. // Firefox
  179. this.tab.addEventListener("TabClose", ev => {
  180. resolve();
  181. }, {once: true});
  182. this.tabBrowser.removeTab(this.tab);
  183. } else {
  184. reject(new UnsupportedOperationError(
  185. `closeTab() not supported in ${this.driver.appName}`));
  186. }
  187. });
  188. }
  189. /**
  190. * Opens a tab with given URI.
  191. *
  192. * @param {string} uri
  193. * URI to open.
  194. */
  195. addTab(uri) {
  196. return this.tabBrowser.addTab(uri, true);
  197. }
  198. /**
  199. * Set the current tab and update remoteness tracking if a tabbrowser is available.
  200. *
  201. * @param {number=} index
  202. * Tab index to switch to. If the parameter is undefined,
  203. * the currently selected tab will be used.
  204. * @param {nsIDOMWindow=} win
  205. * Switch to this window before selecting the tab.
  206. * @param {boolean=} focus
  207. * A boolean value which determins whether to focus
  208. * the window. Defaults to true.
  209. *
  210. * @throws UnsupportedOperationError
  211. * If tab handling for the current application isn't supported.
  212. */
  213. switchToTab(index, win, focus = true) {
  214. if (win) {
  215. this.window = win;
  216. this.tabBrowser = browser.getTabBrowser(win);
  217. }
  218. if (!this.tabBrowser) {
  219. return;
  220. }
  221. if (typeof index == "undefined") {
  222. this.tab = this.tabBrowser.selectedTab;
  223. } else {
  224. this.tab = this.tabBrowser.tabs[index];
  225. if (focus) {
  226. if (this.tabBrowser.selectTab) {
  227. // Fennec
  228. this.tabBrowser.selectTab(this.tab);
  229. } else if ("selectedTab" in this.tabBrowser) {
  230. // Firefox
  231. this.tabBrowser.selectedTab = this.tab;
  232. } else {
  233. throw new UnsupportedOperationError("switchToTab() not supported");
  234. }
  235. }
  236. }
  237. if (this.driver.appName == "Firefox") {
  238. this._browserWasRemote = browser.getBrowserForTab(this.tab).isRemoteBrowser;
  239. this._hasRemotenessChange = false;
  240. }
  241. }
  242. /**
  243. * Registers a new frame, and sets its current frame id to this frame
  244. * if it is not already assigned, and if a) we already have a session
  245. * or b) we're starting a new session and it is the right start frame.
  246. *
  247. * @param {string} uid
  248. * Frame uid for use by Marionette.
  249. * @param the XUL <browser> that was the target of the originating message.
  250. */
  251. register(uid, target) {
  252. let remotenessChange = this.hasRemotenessChange();
  253. if (this.curFrameId === null || remotenessChange) {
  254. if (this.tabBrowser) {
  255. // If we're setting up a new session on Firefox, we only process the
  256. // registration for this frame if it belongs to the current tab.
  257. if (!this.tab) {
  258. this.switchToTab();
  259. }
  260. if (target == browser.getBrowserForTab(this.tab)) {
  261. this.updateIdForBrowser(browser.getBrowserForTab(this.tab), uid);
  262. this.mainContentId = uid;
  263. }
  264. } else {
  265. this._curFrameId = uid;
  266. this.mainContentId = uid;
  267. }
  268. }
  269. // used to delete sessions
  270. this.knownFrames.push(uid);
  271. return remotenessChange;
  272. }
  273. /**
  274. * When navigating between pages results in changing a browser's
  275. * process, we need to take measures not to lose contact with a listener
  276. * script. This function does the necessary bookkeeping.
  277. */
  278. hasRemotenessChange() {
  279. // None of these checks are relevant on b2g or if we don't have a tab yet,
  280. // and may not apply on Fennec.
  281. if (this.driver.appName != "Firefox" ||
  282. this.tab === null ||
  283. browser.getBrowserForTab(this.tab) === null) {
  284. return false;
  285. }
  286. if (this._hasRemotenessChange) {
  287. return true;
  288. }
  289. let currentIsRemote = browser.getBrowserForTab(this.tab).isRemoteBrowser;
  290. this._hasRemotenessChange = this._browserWasRemote !== currentIsRemote;
  291. this._browserWasRemote = currentIsRemote;
  292. return this._hasRemotenessChange;
  293. }
  294. /**
  295. * Flushes any pending commands queued when a remoteness change is being
  296. * processed and mark this remotenessUpdate as complete.
  297. */
  298. flushPendingCommands() {
  299. if (!this._hasRemotenessChange) {
  300. return;
  301. }
  302. this._hasRemotenessChange = false;
  303. this.pendingCommands.forEach(cb => cb());
  304. this.pendingCommands = [];
  305. }
  306. /**
  307. * This function intercepts commands interacting with content and queues
  308. * or executes them as needed.
  309. *
  310. * No commands interacting with content are safe to process until
  311. * the new listener script is loaded and registers itself.
  312. * This occurs when a command whose effect is asynchronous (such
  313. * as goBack) results in a remoteness change and new commands
  314. * are subsequently posted to the server.
  315. */
  316. executeWhenReady(cb) {
  317. if (this.hasRemotenessChange()) {
  318. this.pendingCommands.push(cb);
  319. } else {
  320. cb();
  321. }
  322. }
  323. /**
  324. * Returns the position of the OS window.
  325. */
  326. get position() {
  327. return {
  328. x: this.window.screenX,
  329. y: this.window.screenY,
  330. };
  331. }
  332. };
  333. /**
  334. * The window storage is used to save outer window IDs mapped to weak
  335. * references of Window objects.
  336. *
  337. * Usage:
  338. *
  339. * let wins = new browser.Windows();
  340. * wins.set(browser.outerWindowID, window);
  341. *
  342. * ...
  343. *
  344. * let win = wins.get(browser.outerWindowID);
  345. *
  346. */
  347. browser.Windows = class extends Map {
  348. /**
  349. * Save a weak reference to the Window object.
  350. *
  351. * @param {string} id
  352. * Outer window ID.
  353. * @param {Window} win
  354. * Window object to save.
  355. *
  356. * @return {browser.Windows}
  357. * Instance of self.
  358. */
  359. set(id, win) {
  360. let wref = Cu.getWeakReference(win);
  361. super.set(id, wref);
  362. return this;
  363. }
  364. /**
  365. * Get the window object stored by provided |id|.
  366. *
  367. * @param {string} id
  368. * Outer window ID.
  369. *
  370. * @return {Window}
  371. * Saved window object, or |undefined| if no window is stored by
  372. * provided |id|.
  373. */
  374. get(id) {
  375. let wref = super.get(id);
  376. if (wref) {
  377. return wref.get();
  378. }
  379. }
  380. };