Subscript Loader: Handling JS scope

Anyone who does advanced JavaScript work is familiar with the concept of scope. It causes interesting problems, particularly if you want your script to work with someone else's. Weird Al over at MozillaZine has written up a little known component called the JavaScript subscript loader. The beauty of this component isn't that it can load […]

Anyone who does advanced JavaScript work is familiar with the concept of scope. It causes interesting problems, particularly if you want your script to work with someone else's. Weird Al over at MozillaZine has written up a little known component called the JavaScript subscript loader. The beauty of this component isn't that it can load scripts for you... it's that you can give it a "scope" to play with. That scope can be a simple JavaScript object. (Omitting the second argument means it will use whatever scope it's being loaded from.)

So, if you want your application to accept overlays, you just need a scope registry to prevent conflicts (mostly). Lo and behold:

const scopeRegistry = { subscriptLoader: Components.classes["@mozilla.org/moz/jssubscript-loader;1"] .getService(Components.interfaces.mozIJSSubScriptLoader), registeredScopes: {}, getScope: function getScope(aScopeId) { if (typeof this.registeredScopes[aScopeId] == "undefined") this.registeredScopes[aScopeId] = {}; return this.registeredScopes[aScopeId]; }, loadScriptByScope: function loadScriptByScope(aURL, aScopeId) { if (aScopeId) { var scopeObj = this.getScope(aScopeId); this.subscriptLoader.loadSubScript(aURL, scopeObj); } else { this.subscriptLoader.loadSubScript(aURL); } } }