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