]> git.gir.st - VimFx.git/blob - extension/packages/window-utils.coffee
Add gulp release task
[VimFx.git] / extension / packages / window-utils.coffee
1 { unloader } = require 'unloader'
2
3 #
4 # Waits for a browser window to finish loading before running the callback.
5 #
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".
9 #
10 runOnLoad = (window, callback, winType) ->
11 # Listen for one load event before checking the window type.
12 cb = ->
13 window.removeEventListener('load', arguments.callee, false)
14
15 # Now that the window has loaded, only handle browser windows.
16 if window.document.documentElement.getAttribute('windowtype') == winType
17 callback(window)
18
19 window.addEventListener('load', cb, false)
20
21 #
22 # Add functionality to existing browser windows.
23 #
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".
27 #
28 runOnWindows = (callback, winType) ->
29 # Wrap the callback in a function that ignores failures.
30 watcher = (window) -> try callback(window)
31
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.
40 else
41 runOnLoad(browserWindow, watcher, winType)
42
43 #
44 # Apply a callback to each open and new browser windows.
45 #
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".
49 #
50 watchWindows = (callback, winType) ->
51 # Wrap the callback in a function that ignores failures.
52 watcher = (window) -> try callback(window)
53
54 # Add functionality to existing windows.
55 runOnWindows(callback, winType)
56
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)
61
62 Services.ww.registerNotification(windowWatcher)
63
64 # Make sure to stop watching for windows if we're unloading.
65 unloader.add(-> Services.ww.unregisterNotification(windowWatcher))
66
67 exports.runOnLoad = runOnLoad
68 exports.runOnWindows = runOnWindows
69 exports.watchWindows = watchWindows
Imprint / Impressum