1 { unload } = require 'unload'
3 # Waits for a browser window to finish loading before running the callback
5 # @usage runOnLoad(window, callback): Apply a callback to to run on a window when it loads.
6 # @param [function] callback: 1-parameter function that gets a browser window.
7 # @param [function] winType: a parameter that defines what kind of window is "browser window".
9 runOnLoad = (window, callback, winType) ->
10 # Listen for one load event before checking the window type
12 window.removeEventListener('load', arguments.callee, false)
14 # Now that the window has loaded, only handle browser windows
15 if window.document.documentElement.getAttribute('windowtype') == winType
18 window.addEventListener('load', cb, false)
21 # Add functionality to existing browser windows
23 # @usage runOnWindows(callback): Apply a callback to each open browser window.
24 # @param [function] callback: 1-parameter function that gets a browser window.
25 # @param [function] winType: a parameter that defines what kind of window is "browser window".
27 runOnWindows = (callback, winType) ->
28 # Wrap the callback in a function that ignores failures
29 watcher = (window) -> try callback(window)
31 # Add functionality to existing windows
32 browserWindows = Services.wm.getEnumerator(winType)
33 while browserWindows.hasMoreElements()
34 # Only run the watcher immediately if the browser is completely loaded
35 browserWindow = browserWindows.getNext()
36 if browserWindow.document.readyState == 'complete'
37 watcher(browserWindow)
38 # Wait for the window to load before continuing
40 runOnLoad(browserWindow, watcher, winType)
43 # Apply a callback to each open and new browser windows.
45 # @usage watchWindows(callback): Apply a callback to each browser window.
46 # @param [function] callback: 1-parameter function that gets a browser window.
47 # @param [function] winType: a parameter that defines what kind of window is "browser window".
49 watchWindows = (callback, winType) ->
50 # Wrap the callback in a function that ignores failures
51 watcher = (window) -> try callback(window)
53 # Add functionality to existing windows
54 runOnWindows(callback, winType)
56 # Watch for new browser windows opening then wait for it to load
57 windowWatcher = (subject, topic) ->
58 if topic == 'domwindowopened'
59 runOnLoad(subject, watcher, winType)
61 Services.ww.registerNotification(windowWatcher)
63 # Make sure to stop watching for windows if we're unloading
64 unload -> Services.ww.unregisterNotification(windowWatcher)
66 exports.runOnLoad = runOnLoad
67 exports.runOnWindows = runOnWindows
68 exports.watchWindows = watchWindows