1 { unloader } = require 'unloader'
4 # Waits for a browser window to finish loading before running the callback.
6 # @usage runOnLoad(window, callback): Apply a callback to to run on a window when it loads.
7 # @param [function] callback: 1-parameter function that gets a browser window.
8 # @param [function] winType: a parameter that defines what kind of window is "browser window".
10 runOnLoad = (window, callback, winType) ->
11 # Listen for one load event before checking the window type.
13 window.removeEventListener('load', arguments.callee, false)
15 # Now that the window has loaded, only handle browser windows.
16 if window.document.documentElement.getAttribute('windowtype') == winType
19 window.addEventListener('load', cb, false)
22 # Add functionality to existing browser windows.
24 # @usage runOnWindows(callback): Apply a callback to each open browser window.
25 # @param [function] callback: 1-parameter function that gets a browser window.
26 # @param [function] winType: a parameter that defines what kind of window is "browser window".
28 runOnWindows = (callback, winType) ->
29 # Wrap the callback in a function that ignores failures.
30 watcher = (window) -> try callback(window)
32 # Add functionality to existing windows
33 browserWindows = Services.wm.getEnumerator(winType)
34 while browserWindows.hasMoreElements()
35 # Only run the watcher immediately if the browser is completely loaded.
36 browserWindow = browserWindows.getNext()
37 if browserWindow.document.readyState == 'complete'
38 watcher(browserWindow)
39 # Wait for the window to load before continuing.
41 runOnLoad(browserWindow, watcher, winType)
44 # Apply a callback to each open and new browser windows.
46 # @usage watchWindows(callback): Apply a callback to each browser window.
47 # @param [function] callback: 1-parameter function that gets a browser window.
48 # @param [function] winType: a parameter that defines what kind of window is "browser window".
50 watchWindows = (callback, winType) ->
51 # Wrap the callback in a function that ignores failures.
52 watcher = (window) -> try callback(window)
54 # Add functionality to existing windows.
55 runOnWindows(callback, winType)
57 # Watch for new browser windows opening then wait for it to load.
58 windowWatcher = (subject, topic) ->
59 if topic == 'domwindowopened'
60 runOnLoad(subject, watcher, winType)
62 Services.ww.registerNotification(windowWatcher)
64 # Make sure to stop watching for windows if we're unloading.
65 unloader.add(-> Services.ww.unregisterNotification(windowWatcher))
67 exports.runOnLoad = runOnLoad
68 exports.runOnWindows = runOnWindows
69 exports.watchWindows = watchWindows