2 # Waits for a browser window to finish loading before running the callback
4 # @usage runOnLoad(window, callback): Apply a callback to to run on a window when it loads.
5 # @param [function] callback: 1-parameter function that gets a browser window.
6 # @param [function] winType: a parameter that defines what kind of window is "browser window".
8 runOnLoad = (window, callback, winType) ->
9 # Listen for one load event before checking the window type
11 window.removeEventListener "load", arguments.callee, false
13 # Now that the window has loaded, only handle browser windows
14 if window.document.documentElement.getAttribute("windowtype") == winType
17 window.addEventListener "load", cb, false
20 # Add functionality to existing browser windows
22 # @usage runOnWindows(callback): Apply a callback to each open browser window.
23 # @param [function] callback: 1-parameter function that gets a browser window.
24 # @param [function] winType: a parameter that defines what kind of window is "browser window".
26 runOnWindows = (callback, winType) ->
27 # Wrap the callback in a function that ignores failures
28 watcher = (window) -> try callback(window)
30 # Add functionality to existing windows
31 browserWindows = Services.wm.getEnumerator(winType)
32 while browserWindows.hasMoreElements()
33 # Only run the watcher immediately if the browser is completely loaded
34 browserWindow = browserWindows.getNext()
35 if browserWindow.document.readyState == "complete"
36 watcher(browserWindow);
37 # Wait for the window to load before continuing
39 runOnLoad(browserWindow, watcher, winType)
42 # Apply a callback to each open and new browser windows.
44 # @usage watchWindows(callback): Apply a callback to each browser window.
45 # @param [function] callback: 1-parameter function that gets a browser window.
46 # @param [function] winType: a parameter that defines what kind of window is "browser window".
48 watchWindows = (callback, winType) ->
49 # Wrap the callback in a function that ignores failures
50 watcher = (window) -> try callback(window)
52 # Add functionality to existing windows
53 runOnWindows callback, winType
55 # Watch for new browser windows opening then wait for it to load
56 windowWatcher = (subject, topic) ->
57 if topic == "domwindowopened"
58 runOnLoad subject, watcher, winType
60 Services.ww.registerNotification windowWatcher
62 # Make sure to stop watching for windows if we're unloading
63 unload -> Services.ww.unregisterNotification(windowWatcher)
65 exports.runOnLoad = runOnLoad
66 exports.runOnWindows = runOnWindows
67 exports.watchWindows = watchWindows