Bug 1886451: Add missing ifdef Nightly guards. r=dminor
[gecko.git] / remote / shared / listeners / NavigationListener.sys.mjs
blobc911bb53f6fcd2f5e666bcae986d6087d35a8a85
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/. */
5 const lazy = {};
7 ChromeUtils.defineESModuleGetters(lazy, {
8   EventEmitter: "resource://gre/modules/EventEmitter.sys.mjs",
9 });
11 /**
12  * The NavigationListener simply wraps a NavigationManager instance and exposes
13  * it with a convenient listener API, more consistent with the rest of the
14  * remote codebase. NavigationManager is a singleton per session so it can't
15  * be instanciated for each and every consumer.
16  *
17  * Example:
18  * ```
19  * const onNavigationStarted = (eventName, data = {}) => {
20  *   const { level, message, stacktrace, timestamp } = data;
21  *   ...
22  * };
23  *
24  * const listener = new NavigationListener(this.messageHandler.navigationManager);
25  * listener.on("navigation-started", onNavigationStarted);
26  * listener.startListening();
27  * ...
28  * listener.stopListening();
29  * ```
30  *
31  * @fires message
32  *    The NavigationListener emits "navigation-started", "location-changed" and
33  *    "navigation-stopped" events, with the following object as payload:
34  *      - {string} navigationId - The UUID for the navigation.
35  *      - {string} navigableId - The UUID for the navigable.
36  *      - {string} url - The target url for the navigation.
37  */
38 export class NavigationListener {
39   #listening;
40   #navigationManager;
42   /**
43    * Create a new NavigationListener instance.
44    *
45    * @param {NavigationManager} navigationManager
46    *     The underlying NavigationManager for this listener.
47    */
48   constructor(navigationManager) {
49     lazy.EventEmitter.decorate(this);
51     this.#listening = false;
52     this.#navigationManager = navigationManager;
53   }
55   get listening() {
56     return this.#listening;
57   }
59   destroy() {
60     this.stopListening();
61   }
63   startListening() {
64     if (this.#listening) {
65       return;
66     }
68     this.#navigationManager.on("navigation-started", this.#forwardEvent);
69     this.#navigationManager.on("navigation-stopped", this.#forwardEvent);
70     this.#navigationManager.on("location-changed", this.#forwardEvent);
72     this.#listening = true;
73   }
75   stopListening() {
76     if (!this.#listening) {
77       return;
78     }
80     this.#navigationManager.off("navigation-started", this.#forwardEvent);
81     this.#navigationManager.off("navigation-stopped", this.#forwardEvent);
82     this.#navigationManager.off("location-changed", this.#forwardEvent);
84     this.#listening = false;
85   }
87   #forwardEvent = (name, data) => {
88     this.emit(name, data);
89   };